Commit dff6f518 by hxw

添加配置文件

parent 89d80ae8
test_var=1111
qa_url=http://192.168.1.78:59000/game
cc_url=http://localhost:8070/api/update/data
//condition_backend=http://192.168.1.82
unknown_text=不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧
location_hint=请到%s
game_start_hint=请说开始剧情或者继续剧情
game_module_error=游戏模块出错
# -------------------------------游戏生成---------------------------
delete_old_config_term_error=删除旧数据config失败
delete_old_variable_error=删除旧变量失败
delete_old_category_error=删除旧类别失败
# ----------------------------------------------------------------
unknown_text_description=对于无法识别的问题做出的回答
game_step_description=QA问答游戏进度
star_plot_not_exist=开始剧情不存在,请到剧情列表设置
助手对应的变量
assistant=globalVariable_智能助手
# ------------------------助手情绪--------------
assistant_emotion=正常
talker_pattern=【%s@%s】
# ----------------------------------------------
game_step_format=%s_plot_%s
# ----------------------剧情进度标识-----------------
task_line=任务线_%s进度
task_condition=任务线%s最后一个condition
task_reply=任务线%s最后的回答
plot_status=剧情%s状态
# ---------------------------------------------------
plot_generation_error=剧情接口处理出现异常
默认condition
default_condition=yaobuyao
script_not_exist=话术不存在
goto_condition=yaobuyao
#-------------------话术------------------------
nothing_found=什么都没有
dont_found=没有找到
nowhere_can_go=没有地方可以去了
attribute_hidden=不能看到哦
attr_value_slot=[属性值]
attr_name_slot=[属性名]
npc_name_slot=[人名]
npc_list_slot=[人物列表]
site_slot=[地点名]
site_slot2=[地点]
site_list_slot=[地点列表]
item_list_slot=[物品列表]
item_name_slot=[物品名]
npc_item_list_slot=[人物物品列表]
can_go_site_slot=[可去列表]
path_slot=[途径]
start_slot=
destination_slot=[目的地]
task_description_slot=[任务描述]"
find_item_owner=[物品名]在[人名]身上
#----------------------------------------------
# ---------------------文本解析---------------------
text_parse_error=文本解析出错
automatch_threshold=0.5
game_condition_category=97
service_url=http://192.168.1.178:8081/bot/dialog
options=disable_knowledge_qa,fast_understanding,pattern_cover,no_repeat
automatch_url=http://dev01.centaurstech.com:5700/mermaid/?model=auto-train
idlelimit=180000
condition_generate_url=http://192.168.1.178:1111/conditionProcess
condition_backend_url=http://192.168.1.82:6636/api
style=interrupt,multimatchvalues,bothvalue
fellow=pivot_httppost
post_style1=style=httppost,bothvalue,multimatchvalues
post_style2=style=httppost,multimatchvalues
post_action_head=#actions\r\nname=pivot_httppost\r\nstatus=waiting\r\n%s\r\nserviceURL=%s
# ----------------------condition增删改查异常----------------------------
update_keyword_error=更新关键词单元失败
delete_user_data_error=删除用户数据失败
game_condition_category_id=123
platform_sql_init_error=新平台获取sql连接失败
\ No newline at end of file
#!/bin/bash
mvn clean package -Ppro -Dmaven.test.skip=true
cd target
scp my-app.jar hz1:visualkm/chatbot-backend
cd ..
{"gameStart":[{"conditionName":"start_options","plotText":"请说开始剧情或者继续剧情","id":"start1","place":"加载","branch":[{"curPremise":[{"conditionName":"start_options","cmpType":"match","operator":"Include","keyword":"重新开始"},],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"moveWithPlot":true,"updateKnowledge":{"unknownText":"firstUnknownText",},"extraFeature":"newGame","nextPlotId":"startId",},{"curPremise":[{"conditionName":"start_options","cmpType":"match","operator":"Include","keyword":"+开始+开始游戏+继续游戏+继续"},],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"moveWithPlot":true,"updateKnowledge":{"unknownText":"firstUnknownText",},"extraFeature":"loadLastArchive","nextPlotId":"startId",},{"curPremise":[{"conditionName":"load_game_by_site","cmpType":"match","operator":"Include","keyword":"site_list"},],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"moveWithPlot":true,"updateKnowledge":{"unknownText":"firstUnknownText",},"extraFeature":"loadArchiveBySite","nextPlotId":"startId"},{"curPremise":[],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"moveWithPlot":true,"updateKnowledge":{},"nextPlotId":"start1",},{"curPremise":[{"conditionName":"start_options","cmpType":"match","operator":"Include","keyword":"+存档列表"},],"higherPriority":true,"includeCurInfo":false,"autoJump":false,"hisPremise":[],"extraFeature":"sendArchiveList","moveWithPlot":false,"updateKnowledge":{},"nextPlotId":"start1",}]}]}
\ No newline at end of file
# ------------------------------------------------------------------------------
# 格式
# 意图|语义关系名字|关键词
# name表示可以替换的名字,如物品名、角色名
# attrName是属性名
# qiwu就是玩家“我”
# ------------------------------------------------------------------------------
# 我在哪里
WHERE_I_AM|zainali|+在:哪里+在:哪儿+在:哪+在:位置+在:地点+在:地方+到:哪里+到:地点+到:地方
WHERE_I_AM|wenzainali|+哪:qiwu+地方:qiwu+位置:qiwu+地点:qiwu+哪里:qiwu+哪儿:qiwu+哪:landey+地方:landey+位置:landey+地点:landey+哪里:landey+哪儿:landey
# 我能去哪里
WHERE_CAN_I_GO|choose_gowhere|+哪里:qiwu+哪:qiwu+哪儿:qiwu+地方:qiwu+哪里:去+哪:能去+哪里:能去+哪儿:能去+地方:能去+地方:去+地方:能去+哪里:能去+哪:去+哪:能去+哪儿:去+哪:qiwu+哪:到+哪儿:到+哪里:到
# 周围有什么人
AROUND_NPC|know_exist_what|+周围:人+旁边:人+附近:人+周围:谁+这里:谁+这里:人+有什么:人+里面:人+里面:谁+哪些:人+qiwu:人+qiwu:谁+有:谁+有:人+附近:谁+有:附近+旁边:谁
AROUND_NPC|zhiwen|+这里:谁+这里:谁+谁:在
# 周围有什么npc类别
AROUND_NPC_CLASS|know_exist_what|+周围:name+附近:name
# 周围有什么
AROUND_THINGS|know_exist_what_mohu|+有什么:周围+有什么:附近+有什么:这里+有:哪些:这里+有谁:周围+有什么:里面+有什么:旁边+qiwu:旁边+有什么:这里+有:哪些
# 周围有什么物品
AROUND_ITEM|know_exist_what|+周围:物品+旁边:物品+旁边:东西+周围:东西+附近:物品+附近:东西+这里:物品+这里:东西+有什么:东西+有什么:物品+哪些:物品+哪些:东西+有:东西+里面:物品
AROUND_ITEM|nums|+有:哪些
# AROUND_ITEM|zhiwen|+附近:who+周围:who+旁边:who
# 周围有什么地方
AROUND_PLACE|know_exist_what|+周围:地点+周围:地方+哪些:地方+哪些:地点+旁边:地方+旁边:地点+附近:地方+附近:地点
# 周围有什么物品类别
AROUND_ITEM_CLASS|know_exist_what|+周围:name+附近:name
# 我有什么
WHAT_ITEM_I_HAVE|know_exist_what_mohu|+有什么:qiwu+什么:qiwu+qiwu:东西+qiwu:地方
WHAT_ITEM_I_HAVE|know_exist_what|有什么:东西
WHAT_ITEM_I_HAVE|zhiwen|+qiwu:带
# 里面有谁
WHO_IN_THERE|shishui|+谁:里面+里面:人
# 去xx
GO_TO|yaobuyao|+去:name+到:name
# 怎么找到NPC
HOW_TO_FIND_NPC|xxx|+找到:name
# 你是谁
WHO_YOU_ARE|zhiwen|+botname:谁+botname:干嘛+那个人:谁+人:谁+botname:是+人:是
# 任务是什么
TASK_IS_WHAT|shishenme|+是什么:任务+qiwu:任务
TASK_IS_WHAT|zhiwen|+qiwu:要去
# npc在哪里
NPC_LOCATION|wenzainali|+哪里:name+哪:name+地方:name+地点:name
# 物品在哪里
ITEM_LOCATION|wenzainali|+哪里:name+哪:name+地方:name+地点:name+位置:name+哪儿:name+位置:name
# 怎么找到npc
HOW_FIND_NPC|want_know_zenmezuo|+找到:name
#怎么找到物品
HOW_FIND_ITEM|want_know_zenmezuo|+找到:name
# 沙滩上有什么人
WHAT_NPC_IN_LOCATION|xxx|地点
# xx上有什么东西
WAHT_ITEM_IN_LOCATION|xxx|地点
# 地点上有什么
WHAT_THINGS_IN_LOCATION|xxx|地点
# npc的属性是多少
NPC_ATTR|nums|+name:attrName
NPC_ATTR|shishenme|+name:attrName
# 物品的属性是多少
ITEM_ATTR|nums|+name:attrName
ITEM_ATTR|shishenme|+name:attrName
# 周围有什么物品类别
AOURND_NPC_CLASS|know_exist_what|+周围:name+附近:name
# 怎么去XXX
HOW_TO_THERE|want_know_zenmezuo|+去:name
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>chatbot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>chatbot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>9.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.0</version>
</dependency>
</dependencies>
<build>
<finalName>my-app</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>-Xmx64m</jvmArguments>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<!--资源根目录排除各环境的配置,防止在生成目录中多余其它目录-->
<excludes>
<exclude>test/*</exclude>
<exclude>pro/*</exclude>
<exclude>dev/*</exclude>
</excludes>
<includes>
<include>*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources/${profiles.active}</directory>
</resource>
</resources>
</build>
<profiles>
<profile>
<!-- 本地开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
<activatedProperties>test</activatedProperties>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>pro</id>
<properties>
<profiles.active>pro</profiles.active>
<activatedProperties>pro</activatedProperties>
</properties>
</profile>
</profiles>
</project>
package com.qiwu.chatbotbackend.Config;
import org.springframework.stereotype.Component;
@Component
public class Config {
public static String TEXT_PARSE_ERROR = null;
public static String CONDITION_URL = null;
public static String TEST_VAR = null;
public static String QA_URL = null;
public static String CC_URL = null;
public static String UNKNOWN_TEXT = null;
public static String LOCATION_HINT = null;
public static String GAME_START_HINT = null;
public static String GAME_MODULE_ERROR = null;
public static String DELETE_OLD_CONFIG_TERM_ERROR = null;
public static String DELETE_OLD_VARIABLE_ERROR = null;
public static String DELETE_OLD_CATEGORY_ERROR = null;
public static String UNKNOWN_TEXT_DESCRIPTION = null;
public static String GAME_STEP_DESCRIPTION = null;
public static String START_PLOT_NOT_EXIST = null;
public static String ASSISTANT = null;
public static String ASSISTANT_EMOTION = null;
public static String TASK_DESCRIPTION = null;
public static String TALKER_PATTERN = null;
public static String GAME_STEP_FORMAT = null;
public static String PLOT_STATUS = null;
public static String TASK_LINE = null;
public static String TASK_CONDITION = null;
public static String TASK_REPLY = null;
public static String PLOT_GENERATION_ERROR = null;
//默认condition
public static String DEFAULT_CONDITION = null;
//去xx地方condition
public static String GOTO_CONDITION = null;
public static class Script {
public static String CODE = "subcode";
public static int SIZE = 12;
};
public static String POST_ACTION_ERROR = null;
public static String TOKEN_TIME_OUT = null;
public static String ENCODE_ERROR = null;
//话术
public static String NOTHING_FOUND = null;
public static String DONT_FOUND = null;
public static String NOWHERE_CAN_GO = null;
public static String ATTRIBUTE_HIDDEN = null;
public static String ATTR_VALUE_SLOT = null;
public static String ATTR_NAME_SLOT = null;
public static String NPC_NAME_SLOT = null;
public static String NPC_LIST_SLOT = null;
public static String SITE_SLOT = null;
public static String SITE_SLOT2 = null;
public static String ITEM_LIST_SLOT = null;
public static String ITEM_NAME_SLOT = null;
public static String NPC_ITEM_LIST_SLOT = null;
public static String CAN_GO_SITE_SLOT = null;
public static String PATH_SLOT = null;
public static String START_SLOT = null;
public static String DESTINATION_SLOT = null;
public static String SITE_LIST_SLOT = null;
public static String TASK_DESCRIPTION_SLOT = null;
public static String FIND_ITEM_OWNER = null;
//生成action
public static String GAME_CONDITION_CATEGORY = null;
public static String AUTOMATCH_THRESHOLD = null;
public static String IDLE_LIMIT = null;
public static String CONDITION_BACKEND_URL = null;
public static String CONDITION_GENERATE_URL= null;
public static String OPTIONS = null;
public static String STYLE = null;
public static String AUTOMATCH_URL = null;
public static String SERVICE_URL = null;
public static String FELLOW = null;
public static String POST_STYLE1 = null;
public static String POST_STYLE2 = null;
public static String POST_ACTION_HEAD=null;
//condition增删改查异常
public static String UPDATE_KEYWORD_ERROR = null;
public static String DELETE_USER_DATA_ERROR = null;
}
package com.qiwu.chatbotbackend.Config;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Properties;
import java.util.Set;
public class ConfigInitializer {
private static final String CONFIGFILE = "config.properties";
private static final String CLASSPREFIX = "com.qiwu.chatbotbackend.config.config";
/**
* 读取配置文件
*/
public static void init() {
InputStream configInputStream;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(CONFIGFILE));
Properties properties = new Properties();
properties.load(bufferedReader);
initNextLevel(properties, Config.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static void initNextLevel(Properties properties, Class nowClass) throws IllegalAccessException {
String baseClassName = nowClass.getName().toLowerCase().replaceAll("\\$", "\\.");
String shortName = baseClassName.replaceAll(CLASSPREFIX, "").replaceFirst("\\.", "");
//key集合
Set<Object> keys = properties.keySet();
for (Field field : nowClass.getFields()) {
if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
String classParam = field.getName().toLowerCase();
if (shortName.equals("")) {
if (keys.contains(classParam)) {
pushNewValue(classParam, properties, field);
}
} else {
if (keys.contains(shortName + "." + classParam)) {
pushNewValue(shortName + "." + classParam, properties, field);
}
}
}
}
for (Class<?> aClass : nowClass.getClasses()) {
initNextLevel(properties, aClass);
}
}
public static void pushNewValue(String classParam, Properties properties, Field field) throws IllegalAccessException {
String value = properties.getProperty(classParam);
if (value != null) {
Class<?> type = field.getType();
if (type.equals(int.class))
field.set(null, Integer.valueOf(value));
else if (type.equals(String.class))
field.set(null, value);
else if (type.equals(long.class))
field.set(null, Long.valueOf(value));
else if (type.equals(boolean.class))
field.set(null, Boolean.valueOf(value));
else if (type.isEnum())
field.set(null, Enum.valueOf((Class<Enum>) type, value.toUpperCase()));
}
}
}
...@@ -14,6 +14,8 @@ public class C3p0Utils { ...@@ -14,6 +14,8 @@ public class C3p0Utils {
//通过标识名来创建相应连接池 //通过标识名来创建相应连接池
static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");
//通过标识名来创建相应连接池
static ComboPooledDataSource dataSource2 = new ComboPooledDataSource("mysql2");
//从连接池中取用一个连接 //从连接池中取用一个连接
public static Connection getConnection() throws SQLException { public static Connection getConnection() throws SQLException {
...@@ -26,6 +28,17 @@ public class C3p0Utils { ...@@ -26,6 +28,17 @@ public class C3p0Utils {
} }
} }
//从连接池中取用一个连接
public static Connection getEngineConnection() throws SQLException {
try {
return dataSource2.getConnection();
} catch (Exception e) {
logger.error("Exception in C3p0Utils!", e);
throw e;
}
}
//释放连接回连接池 //释放连接回连接池
public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException { public static void close(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException {
if (rs != null) { if (rs != null) {
......
package com.qiwu.chatbotbackend.db; package com.qiwu.chatbotbackend.db;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.actiongenerate.entity.BotInfo;
import com.qiwu.actiongenerate.entity.Condition;
import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.entity.ArchiveInfo;
import com.qiwu.chatbotbackend.gameDesign.ElementConstructor; import com.qiwu.chatbotbackend.gameDesign.ElementConstructor;
...@@ -10,6 +12,8 @@ import java.util.Iterator; ...@@ -10,6 +12,8 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static com.qiwu.chatbotbackend.Config.Config.*;
public class SqlHelper { public class SqlHelper {
private Connection conn = null; private Connection conn = null;
/* /*
...@@ -33,55 +37,377 @@ public class SqlHelper { ...@@ -33,55 +37,377 @@ public class SqlHelper {
} }
} }
/* //----------------------------------------condition操作---------------------------------------------------------------
public boolean insertAction(QuestionKeyWord qkw){ //------------------------------------------------------------------------------------------------------------
String sql = "insert into user_info (chat_key,action_name) values(?,?)";
boolean b = false;
public Boolean deleteUserData(int botId){
String sql1 = "delete from chatbot_config where botId = ?";
String sql2 = "delete from chatbot_condition where botId = ?";
String sql3 = "delete from config_categories where botId = ?";
String sql4 = "delete from chatbot_variable where botId = ?";
Boolean b1, b2, b3, b4;
try{
PreparedStatement ps1 = conn.prepareStatement(sql1);
ps1.setInt(1, botId);
b1 = ps1.execute();
PreparedStatement ps2 = conn.prepareStatement(sql2);
ps2.setInt(1, botId);
b2 = ps1.execute();
PreparedStatement ps3 = conn.prepareStatement(sql3);
ps3.setInt(1, botId);
b3 = ps1.execute();
PreparedStatement ps4 = conn.prepareStatement(sql4);
ps4.setInt(1, botId);
b4 = ps1.execute();
} catch (SQLException e) {
System.out.println(DELETE_USER_DATA_ERROR);
e.printStackTrace();
return false;
}
return b1&&b2&&b3&&b4;
}
public Boolean batchInsertCondition(List<String[]> insertList){
int count[];
boolean insertFlag = true;
String sql = "", varName, varValue, description;
try {
conn.setAutoCommit(false);
sql = "insert into chatbot_condition (botId, conditionData, categoryInfo, actionText, active) values(?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for(String[] elements:insertList){
ps.setString(1, elements[0]);
ps.setString(2, elements[1]);
ps.setString(3, elements[2]);
ps.setString(4, elements[3]);
ps.setString(5, elements[4]);
ps.addBatch();
}
count = ps.executeBatch();
conn.commit();
for (int i : count) {
if (i == 0) {
conn.rollback();
System.out.println("======出现异常,回滚=========");
insertFlag = false;
}
}
ps.close();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("------出现异常,回滚----------");
e.printStackTrace();
}
return insertFlag;
}
public List<String> queryActionTextList(int botId){
String sql = "select actionText from chatbot_condition where botId= ?";
String pre_name = "";
List<String> actionTextList = new ArrayList<String>();
try{ try{
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,qkw.getChatKey()); ps.setInt(1,botId);
ps.setString(2,qkw.getActionName()); ResultSet rs = ps.executeQuery();
b = ps.execute(); while(rs.next()){
return b; actionTextList.add(rs.getString("actionText"));
} catch(Exception e){ }
}catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return b; return actionTextList;
} }
public boolean updateAction(QuestionKeyWord qkw){ public Condition queryActiveCondition(int botId){
String sql = "update user_info set action_name=? where chat_key=?"; Condition condition = null;
boolean b = false;
String sql = "select * from chatbot_condition where active= 1";
String pre_name = "";
List<String> actionTextList = new ArrayList<String>();
try{ try{
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,qkw.getActionName()); ResultSet rs = ps.executeQuery();
ps.setString(2,qkw.getChatKey()); if(rs.next()){
b = ps.execute(); condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
return b; rs.getString("conditionData"), rs.getString("actionText"),
} catch (SQLException e) { rs.getString("categoryStr"), rs.getString("active"));
}
}catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return b; return condition;
} }
public String queryActionByKey(String chat_key){
String sql = "select * from user_info where chat_key= ?";
public List<String> queryConditionCategoriesById(int botId){
String sql = "select categoryStr from chatbot_condition where botId= ?";
String pre_name = ""; String pre_name = "";
List<String> categoryList = new ArrayList<String>();
try{ try{
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,chat_key); ps.setInt(1,botId);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if(rs.next()) while(rs.next()){
return rs.getString("action_name"); categoryList.add(rs.getString("categoryStr"));
}
}catch(Exception e){
e.printStackTrace();
}
return categoryList;
}
public BotInfo queryBotInfo(int botId){
String sql = "select * from bot_info where botId = ?";
BotInfo botInfo = null;
try{
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,botId);
ResultSet rs = ps.executeQuery();
if(rs.next()){
botInfo = new BotInfo(rs.getInt("botId"), rs.getString("welcomText"), rs.getString("goodbyeText"), rs.getString("postURL"), rs.getString("defaultConfigCategory"),
rs.getString("bothValue"), rs.getString("queryTextTransfer"));
}
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return "empty"; return botInfo;
}
public Boolean updateConditionById(Condition condition){
boolean b;
try {
String sql = "update chatbot_condition set conditionData = ?, actionText = ?, categoryInfo = ?, active = ? where botId = ? and conditionId=?";
PreparedStatement ps1 = conn.prepareStatement(sql);
ps1.setString(1, condition.getConditionJsonText());
ps1.setString(2, condition.getActionText());
ps1.setString(3, condition.getCategory());
ps1.setString(4, condition.getActive());
ps1.setInt(5, condition.getBotId());
ps1.setInt(6, condition.getConditionId());
b = ps1.execute();
ps1.close();
return b;
} catch (SQLException e) {
System.out.println(DELETE_OLD_CONFIG_TERM_ERROR);
e.printStackTrace();
return false;
}
}
public boolean batchUpdateCondition(int botId, List<Condition> conditionList) {
int count[];
boolean insertFlag = true;
try {
conn.setAutoCommit(false);
String sql = "update chatbot_condition set conditionData = ?, actionText = ?, categoryInfo = ?, active = ? where botId = ? and conditionId=?";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for(Condition condition:conditionList){
ps.setString(1, condition.getConditionJsonText());
ps.setString(2, condition.getActionText());
ps.setString(3, condition.getCategory());
ps.setString(4, condition.getActive());
ps.setInt(5, condition.getBotId());
ps.setInt(6, condition.getConditionId());
ps.addBatch();
}
count = ps.executeBatch();
conn.commit();
for (int i : count) {
if (i == 0) {
conn.rollback();
System.out.println("======出现异常,回滚=========");
insertFlag = false;
}
}
ps.close();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("------出现异常,回滚----------");
e.printStackTrace();
}
return insertFlag;
}
public List<Condition> queryConditionByCategory(String category){
boolean b;
List<Condition> conditionList = new ArrayList<Condition>();
Condition condition = null;
try {
String sql = "query chatbot_condition wher botId = ? where categoryStr = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, category);
ResultSet rs = ps.executeQuery();
while(rs.next()){
condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
rs.getString("conditionData"), rs.getString("actionText"),
rs.getString("categoryStr"), rs.getString("active"));
conditionList.add(condition);
}
ps.close();
rs.close();
return conditionList;
} catch (SQLException e) {
System.out.println(DELETE_OLD_CONFIG_TERM_ERROR);
e.printStackTrace();
return conditionList;
}
} }
*/
public List<Condition> queryConditionByCategory(int botId, String category){
boolean b;
List<Condition> conditionList = new ArrayList<Condition>();
Condition condition = null;
try {
String sql = "select * from chatbot_condition wher botId = ? and categoryStr = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, botId);
ps.setString(2, category);
ResultSet rs = ps.executeQuery();
while(rs.next()){
condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
rs.getString("conditionData"), rs.getString("actionText"),
rs.getString("categoryStr"), rs.getString("active"));
conditionList.add(condition);
}
ps.close();
rs.close();
return conditionList;
} catch (SQLException e) {
System.out.println(DELETE_OLD_CONFIG_TERM_ERROR);
e.printStackTrace();
return conditionList;
}
}
public Condition queryConditionByConditionId(int botId, int conditionId){
boolean b;
List<Condition> conditionList = new ArrayList<Condition>();
Condition condition = null;
try {
String sql = "select * from chatbot_condition wher botId = ? and conditionId = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, botId);
ps.setInt(2, conditionId);
ResultSet rs = ps.executeQuery();
if(rs.next()){
condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
rs.getString("conditionData"), rs.getString("actionText"),
rs.getString("categoryStr"), rs.getString("active"));
}
ps.close();
rs.close();
return condition;
} catch (SQLException e) {
System.out.println(DELETE_OLD_CONFIG_TERM_ERROR);
e.printStackTrace();
return condition;
}
}
public List<Condition> queryConditionAll(int botId){
boolean b;
List<Condition> conditionList = new ArrayList<Condition>();
Condition condition = null;
try {
String sql = "select * from chatbot_condition wher botId = ? where botId = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, botId);
ResultSet rs = ps.executeQuery();
while(rs.next()){
condition = new Condition(rs.getInt("botId"), rs.getInt("conditionId"),
rs.getString("conditionData"), rs.getString("actionText"),
rs.getString("categoryStr"), rs.getString("active"));
conditionList.add(condition);
}
ps.close();
rs.close();
return conditionList;
} catch (SQLException e) {
System.out.println(DELETE_OLD_CONFIG_TERM_ERROR);
e.printStackTrace();
return conditionList;
}
}
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
private static void releaseSource(Connection _conn, PreparedStatement _st, ResultSet _rs) throws SQLException { private static void releaseSource(Connection _conn, PreparedStatement _st, ResultSet _rs) throws SQLException {
C3p0Utils.close(_conn, _st, _rs); C3p0Utils.close(_conn, _st, _rs);
...@@ -152,7 +478,7 @@ public class SqlHelper { ...@@ -152,7 +478,7 @@ public class SqlHelper {
return b; return b;
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("删除旧数据config失败"); System.out.println(DELETE_OLD_CONFIG_TERM_ERROR);
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
...@@ -172,7 +498,7 @@ public class SqlHelper { ...@@ -172,7 +498,7 @@ public class SqlHelper {
return b; return b;
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("删除旧数据variable失败"); System.out.println(DELETE_OLD_VARIABLE_ERROR);
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
...@@ -193,7 +519,7 @@ public class SqlHelper { ...@@ -193,7 +519,7 @@ public class SqlHelper {
return b; return b;
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("删除旧数据category失败"); System.out.println(DELETE_OLD_CATEGORY_ERROR);
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
......
...@@ -31,6 +31,7 @@ public class Action { ...@@ -31,6 +31,7 @@ public class Action {
//this.activePriority = priority; //this.activePriority = priority;
} }
/** /**
* *
* @param originAction 这个action的初始状态 * @param originAction 这个action的初始状态
...@@ -50,15 +51,17 @@ public class Action { ...@@ -50,15 +51,17 @@ public class Action {
this.id = originAction.id; this.id = originAction.id;
this.configName = originAction.configName; this.configName = originAction.configName;
this.status = originAction.status; this.status = originAction.status;
//this.activePriority = originAction.activePriority + basePriority + 1; //激活会多一个优先级 this.priority = originAction.priority + basePriority + 1; //如果激活的配置没有条件
this.priority = originAction.priority + basePriority + 1;
//如果激活originAction的action,它的辅助优先级高于originAction,那么。。 this.auxiliaryPriority = originAction.auxiliaryPriority + baseAuxiliaryPriority; //优先级为两者之和
if(baseAuxiliaryPriority > originAction.auxiliaryPriority) // //如果激活originAction的action,它的辅助优先级高于originAction,那么。。
this.auxiliaryPriority = baseAuxiliaryPriority; // if(baseAuxiliaryPriority > originAction.auxiliaryPriority)
else // this.auxiliaryPriority = baseAuxiliaryPriority;
this.auxiliaryPriority = originAction.auxiliaryPriority; // else
// this.auxiliaryPriority = originAction.auxiliaryPriority;
//
// this.auxiliaryPriority = this.getAuxiliaryPriority() + 1;
} }
public Action() { public Action() {
......
...@@ -92,25 +92,29 @@ public class ChatCache implements DisposableBean { ...@@ -92,25 +92,29 @@ public class ChatCache implements DisposableBean {
public void destroy() throws IOException { public void destroy() throws IOException {
} }
public ChatCache(UserInfo userInfo, String userKey, String randKey) throws Exception { public ChatCache(UserInfo userInfo, String userKey, String randKey, String botType) throws Exception {
try {
gameEnv = new GameEnv(userInfo.botAccount); if(botType.equals("game")) {
} catch (Exception e) { try {
System.out.println(ENV_ERROR); this.gameEnv = new GameEnv(userInfo.botAccount);
System.out.println("初始化时:" + this.gameEnv);
infoPoint.put("error_message", ENV_ERROR); } catch (Exception e) {
e.printStackTrace(); System.out.println(ENV_ERROR);
this.infoPoint.put("error_message", ENV_ERROR);
e.printStackTrace();
}
} }
String k; String k;
this.botAccount = userInfo.botAccount; this.botAccount = userInfo.botAccount;
infoPoint = new HashMap<String, String>(); this.infoPoint = new HashMap<String, String>();
Iterator<String> iit = userInfo.varInitialMap.keySet().iterator(); Iterator<String> iit = userInfo.varInitialMap.keySet().iterator();
while (iit.hasNext()) { while (iit.hasNext()) {
k = iit.next(); k = iit.next();
infoPoint.put(k, userInfo.varInitialMap.get(k)); this.infoPoint.put(k, userInfo.varInitialMap.get(k));
} }
infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); this.infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
this.randKey = randKey; this.randKey = randKey;
this.userKey = userKey; this.userKey = userKey;
......
package com.qiwu.chatbotbackend.entity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ConfigTermText implements Cloneable{
public static ThreadLocal<Integer> iterNum=new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 0;
}
};
private int id = 0;
private String jCurPremise = "";
private String jHisPremise = "";
private String jFeature = "";
private String jNextStep = "";
private String jReply = "";
private String jAuxiliaryPriority = "0";
private int jStatus = 0;
private String curPremise = "";
private String hisPremise = "";
private String feature = "";
private String reply = "";
private String nextStep = "";
private String updateKnowledge = "";
private String nextStepStatus = "return";
private String configName = "";
private String auxiliaryPriority = "1";
private String status = "waiting";
public void setjStatus(int jStatus) {
this.jStatus = jStatus;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
public String getCurPremise() {
return curPremise;
}
public String getNextStep() {
return nextStep;
}
public void setNextStep(String nextStep) {
this.nextStep = nextStep;
}
public String getConfigName() {
return configName;
}
public void setConfigName(String configName, Boolean append) {
if(append) {
iterNum.set(iterNum.get() + 1);
System.out.println("iterNum:" + iterNum.get());
//iterNum++;
this.configName = configName + "_" + iterNum.get();
}else{
this.configName = configName;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getjCurPremise() {
return jCurPremise;
}
public void setjCurPremise(String jCurPremise) {
this.jCurPremise = jCurPremise;
}
public String getjHisPremise() {
return jHisPremise;
}
public void setjHisPremise(String jHisPremise) {
this.jHisPremise = jHisPremise;
}
public String getjFeature() {
return jFeature;
}
public void setjFeature(String jFeature) {
this.jFeature = jFeature;
}
public String getjNextStep() {
return jNextStep;
}
public void setjNextStep(String jNextStep) {
this.jNextStep = jNextStep;
}
public String getjReply() {
return jReply;
}
public void setjReply(String jReply) {
this.jReply = jReply;
}
public String getjAuxiliaryPriority() {
return jAuxiliaryPriority;
}
public void setjAuxiliaryPriority(String jAuxiliaryPriority) {
this.jAuxiliaryPriority = jAuxiliaryPriority;
}
public int getjStatus() {
return jStatus;
}
public void setCurPremise(String curPremise) {
this.curPremise = curPremise;
}
public String getHisPremise() {
return hisPremise;
}
public void setHisPremise(String hisPremise) {
this.hisPremise = hisPremise;
}
public String getReply() {
return reply;
}
public void setReply(String reply) {
this.reply = reply;
}
public String getAuxiliaryPriority() {
return auxiliaryPriority;
}
public String getStatus() {
return status;
}
public String getNextStepStatus() {
return nextStepStatus;
}
public String getUpdateKnowledge() {
return updateKnowledge;
}
public void setUpdateKnowledge(String updateKnowledge) {
this.updateKnowledge = updateKnowledge;
}
static Map<String, String> statusMap = new HashMap<String, String>() {
{
put("return", "return");
put("return-1", "back");
put("return-0", "stay");
put("activate", "activate");
put("activate:after", "activate:after");
}
};
public void setStatus(String status) {
this.status = status;
}
public void setAuxiliaryPriority(String auxiliaryPriority) {
this.auxiliaryPriority = auxiliaryPriority;
}
public void setNextStepStatus(String nextStepStatus) {
this.nextStepStatus = nextStepStatus;
}
public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) {
this.curPremise = curPremise;
this.hisPremise = hisPremise;
this.feature = feature;
if (!updateKnowledge.equals(""))
this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge;
this.reply = reply;
this.nextStep = nextStep;
}
public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map<String, String> autoJumpUpdateKnowledge) {
this.curPremise = curPremise;
this.hisPremise = hisPremise;
this.feature = feature;
this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge);
//if (!updateKnowledge.equals(""))
// this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge;
this.reply = reply;
this.nextStep = nextStep;
}
public ConfigTermText(List<Premise> curPremise, List<Premise> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) {
this.curPremise = appendPremiseStr(curPremise, extraCP);
this.hisPremise = appendPremiseStr(hisPremise, extraHP);
this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK);
this.feature = feature;
this.reply = reply;
this.nextStep = nextStep;
this.auxiliaryPriority = auxiliaryPriority;
}
public String appendPremiseStr(List<Premise> premises, String extraPremise) {
StringBuffer sb = new StringBuffer();
String premiseStr = "", conditionName;
Map<String ,Integer> nameCount = new HashMap<String , Integer>();
for (Premise premise : premises){
//设置初始值
//System.out.println("nameCount" + nameCount);
conditionName = premise.getConditionName();
nameCount.putIfAbsent(conditionName, 0);
//nameCount加一
nameCount.put(conditionName, nameCount.get(conditionName) + 1);
//在conditionName后添加count
if(nameCount.get(conditionName) > 1) {
premise.setConditionName(conditionName + nameCount.get(conditionName));
}
sb.append(",");
sb.append(premise.getConditionName());
sb.append("::");
sb.append(premise.getCmpType());
sb.append("-");
sb.append(premise.getOperator());
sb.append("=");
sb.append(premise.getKeyword());
}
if (sb.length() > 0)
sb.deleteCharAt(0); //删除第一个逗号
if (!extraPremise.equals("")) {
if (sb.length() == 0)
sb.append(extraPremise);
else
sb.append("," + extraPremise);
} else if (sb.length() == 0) {
sb.append(" ");
}
premiseStr = sb.toString();
return premiseStr;
}
public String appendKnowledgeStr(Map<String, String> knowledge, String extraKL) {
StringBuffer sb = new StringBuffer();
String varName = "", varValue = "", knowledgeStr;
Iterator<String> iit = knowledge.keySet().iterator();
Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后
String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = "";
while (iit.hasNext()) {
varName = iit.next();
varValue = knowledge.get(varName);
if(varValue.startsWith("updateFollowerLocation")){
delayUpdateFollowerLocation = true;
delayUpdateFollowerLocationKey = varName;
delayUpdateFollowerLocationValue = varValue;
continue;
}
sb.append("-<-").append(varName).append(":").append(varValue);
}
if (!extraKL.equals("")) {
sb.append("-<-" + extraKL);
}
if(delayUpdateFollowerLocation){
sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue);
}
if (sb.length() > 0)
knowledgeStr = "updateKnowledge" + sb.toString();
else
knowledgeStr = "";
return knowledgeStr;
}
public void appendJPremise(JSONArray premiseList, String premise, Map<String, String> conditionDescription) {
//System.out.println(premise);
String pair1[] = premise.split("=", 2);
String key = pair1[0];
String keywords = pair1[1];
String pair2[] = key.split("::");
String conditionName = pair2[0];
String pair3[] = pair2[1].split("-");
String cmpType = pair3[0];
String operator = "";
if (pair3.length > 1)
operator = pair3[1];
String question = "";
if (conditionDescription.get(conditionName) != null)
question = conditionDescription.get(conditionName);
JSONObject premiseJ = new JSONObject();
premiseJ.put("keywords", keywords);
premiseJ.put("actionName", conditionName);
premiseJ.put("cmpType", cmpType);
premiseJ.put("question", question);
premiseJ.put("operator", operator);
premiseList.add(premiseJ);
}
public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map<String, String> conditionDescription) {
String pair[] = knowledge.split(":", 2);
if (knowledge.equals("") || pair.length < 2)
return;
String question = "";
if (conditionDescription.get(pair[0]) != null)
question = conditionDescription.get(pair[0]);
JSONObject knowledgeJ = new JSONObject();
knowledgeJ.put("variableName", pair[0]);
knowledgeJ.put("keyword", pair[1]);
knowledgeList.add(knowledgeJ);
}
public void appendJNextStep(JSONArray nextStepList, String next, Map<String, String> conditionDescription) {
String pair[] = next.split("-");
JSONObject nextStepJ = new JSONObject();
JSONArray exceptJ = new JSONArray();
for (int i = 1; i < pair.length; i++)
exceptJ.add(pair[i]);
String question = "";
if (conditionDescription.get(pair[0]) != null)
question = conditionDescription.get(pair[0]);
nextStepJ.put("nextStep", pair[0]);
nextStepJ.put("except", exceptJ);
nextStepJ.put("nextStepText", question);
nextStepList.add(nextStepJ);
}
public JSONObject toJson(Map<String, String> conditionDescription) {
JSONObject data = new JSONObject();
JSONArray curPremiseList = new JSONArray();
JSONArray hisPremiseList = new JSONArray();
//添加当前对话内容
for (String premise : curPremise.split(",")) {
if (!premise.equals("") && !premise.equals(" "))
appendJPremise(curPremiseList, premise, conditionDescription);
}
data.put("currentPremiseList", curPremiseList);
//添加已知信息的内容
for (String premise : hisPremise.split(",")) {
if (!premise.equals("") && !premise.equals(" "))
appendJPremise(hisPremiseList, premise, conditionDescription);
}
data.put("historyPremiseList", hisPremiseList);
//添加下一步状态
//添加configName
data.put("configName", configName);
//添加config状态
data.put("configStatus", jStatus);
boolean doPost = false;
String postURL = "", postType = "all", pair[];
for (String feat : feature.split(",")) {
if (feat.startsWith("post")) {
doPost = true;
pair = feat.substring(0, feat.length() - 1).split("\\(", 2);
postURL = pair[1];
postType = pair[0].split("::")[1];
}else if(feat.equals("return-0")){
nextStepStatus = "return-0";
}else if(feat.equals("activate")){
nextStepStatus = "activate";
}else if(feat.equals("activate:after")){
nextStepStatus = "activate:after";
}
}
data.put("nextStepStatus", statusMap.get(nextStepStatus));
//添加post参数
data.put("doPost", doPost);
data.put("postURL", postURL);
data.put("postType", postType);
//添加回答
data.put("reply", reply);
//添加config类别id
data.put("categoryId", 0);
//添加辅助优先级
data.put("auxiliaryPriority", auxiliaryPriority);
//添加更新答案处的信息
JSONArray knowledgeList = new JSONArray();
if (!updateKnowledge.equals("")) {
for (String knowledge : updateKnowledge.split("-<-")) {
appendJKnowledge(knowledgeList, knowledge, conditionDescription);
}
}
data.put("updateKnowledge", knowledgeList);
//添加下一步
JSONArray nextStepList = new JSONArray();
for (String next : nextStep.split(",")) {
appendJNextStep(nextStepList, next, conditionDescription);
}
data.put("nextStepList", nextStepList);
return data;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(curPremise).append("|");
sb.append(hisPremise);
sb.append("|").append(feature).append(",");
sb.append(updateKnowledge).append(",");
sb.append(nextStepStatus).append( "|");
sb.append("auxiliaryPriority=");
sb.append(auxiliaryPriority).append("|").append("configName=");
sb.append(configName);
sb.append("|=>|").append(reply);
sb.append("|").append("nextStep=");
sb.append(nextStep).append("|");
sb.append("status=").append(status);
sb.append("|").append("configId=");
return sb.toString();
}
public Object clone() {
Object o=null;
try{
o= super.clone();
}catch(CloneNotSupportedException e){
System.out.println(e.toString());
}
return o;
}
public static void activateCopy(ConfigTermText configTermText, List<ConfigTermText> configTermTextList, String name){
configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}");
ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone();
if(configTermText2.getUpdateKnowledge().equals(""))
configTermText2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}");
else
configTermText2.setUpdateKnowledge(configTermText2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}");
configTermText2.setConfigName(name, true);
configTermTextList.add(configTermText2);
}
public ConfigTermText simpleCopy(ConfigTermText configTermText){
ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone();
return configTermText2;
}
}
...@@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; ...@@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
...@@ -25,46 +25,36 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -25,46 +25,36 @@ public class CharacterConstructor extends ElementConstructor {
try { try {
String pattern1 = keywordMap.get("npc_location_pattern").toString(); //FIND_NPC_LOCATION
String pattern;
StringBuffer onlineModeTalkers = new StringBuffer(","); StringBuffer onlineModeTalkers = new StringBuffer(",");
JSONArray allNPC = gameElements.getJSONArray("npc"); JSONArray allNPC = gameElements.getJSONArray("npc");
Map<String, String> attribute = null; Map<String, String> attribute = null;
HashSet<String> classSet = new HashSet<String>(); HashSet<String> classSet = new HashSet<String>();
List<String[]> replaceList = new ArrayList<String[]>();
keywordMap.putIfAbsent("npc_wenzainali", new StringBuffer());
keywordMap.putIfAbsent("npc_shishenme", new StringBuffer());
keywordMap.putIfAbsent("npc_know_exist_what", new StringBuffer());
keywordMap.putIfAbsent("npc_nums", new StringBuffer());
keywordMap.putIfAbsent("npc_want_know_zenmezuo", new StringBuffer());
keywordMap.putIfAbsent("talker_zhiwen", new StringBuffer());
//与物品属性查询相关的所有condition
String attrRelateConditions[] = {"nums", "shishenme"};
//与物品类查询相关的所有condition
String classRelateConditions[] = {"know_exist_what" };
String locationRelateConditions[] = {"wenzainali"}; copyPattern("HOW_FIND_NPC");
copyPattern("NPC_LOCATION");
copyPattern("AOURND_NPC_CLASS");
copyPattern("NPC_ATTR");
copyPattern("WHO_YOU_ARE");
//与说话的人相关的condition
String talkerRelateConditions[] = {"zhiwen"};
//如何找到×××××× ,这样的condition
String findRelateConditions[] = {"want_know_zenmezuo"};
String findPattern = keywordMap.get("find_pattern").toString();
for (JSONObject character : allNPC.toJavaList(JSONObject.class)) {
replaceList.clear();
String classPattern = keywordMap.get("npc_class_pattern").toString();
name = character.getString("name");
for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { replaceList.add(new String[]{"name", name});
name = character.getString("name");
//找到所有处于离线模式的npc //找到所有处于离线模式的npc
...@@ -79,8 +69,9 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -79,8 +69,9 @@ public class CharacterConstructor extends ElementConstructor {
appendPOS(POS, name, "人名"); appendPOS(POS, name, "人名");
appendPOS(POS, className, "人名"); appendPOS(POS, className, "人名");
keywordMap.get("npc_want_know_zenmezuo").append(findPattern.replace("name", name));
keywordMap.get("npc_" + locationRelateConditions[0]).append(pattern1.replace("name", name)); appendReplacedKeyword("NPC_LOCATION", replaceList);
appendReplacedKeyword("HOW_FIND_NPC", replaceList);
//添加别名 //添加别名
if(character.containsKey("nickname")){ if(character.containsKey("nickname")){
...@@ -88,8 +79,10 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -88,8 +79,10 @@ public class CharacterConstructor extends ElementConstructor {
if(!nickname.equals("")) { if(!nickname.equals("")) {
appendPOS(POS, nickname, "人名"); appendPOS(POS, nickname, "人名");
nameList.add(nickname); nameList.add(nickname);
keywordMap.get("npc_want_know_zenmezuo").append(findPattern.replace("name", nickname));
keywordMap.get("npc_" + locationRelateConditions[0]).append(pattern1.replace("name", nickname)); replaceList.get(0)[1] = nickname;
appendReplacedKeyword("NPC_LOCATION", replaceList);
appendReplacedKeyword("HOW_FIND_NPC", replaceList);
} }
} }
} }
...@@ -99,97 +92,69 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -99,97 +92,69 @@ public class CharacterConstructor extends ElementConstructor {
//添加类名称 //添加类名称
if (!classSet.contains(className)) { if (!classSet.contains(className)) {
classSet.add(className); classSet.add(className);
keywordMap.get("npc_know_exist_what").append(classPattern.replace("name", className)); //替换后的名字改为类名
replaceList.get(0)[1] = className;
appendReplacedKeyword("AOURND_NPC_CLASS", replaceList);
} }
attribute = gameElements.toJavaObject(character.getJSONObject("attr"), Map.class); attribute = gameElements.toJavaObject(character.getJSONObject("attr"), Map.class);
//替换后的名字改为npc名
replaceList.get(0)[1] = name;
replaceList.add(new String[]{"attrName", ""});
for(String attrName:attribute.keySet()){ for(String attrName:attribute.keySet()){
replaceList.get(1)[1] = attrName;
appendPOS(POS, attrName, "名词"); appendPOS(POS, attrName, "名词");
for(String NPCName:nameList) { for(String NPCName:nameList) {
appendReplacedKeyword("NPC_ATTR", replaceList);
for (String condition : attrRelateConditions) {
keywordMap.get("npc_" + condition).append("+").append(NPCName).append(":").append(attrName);
}
} }
} }
} }
replaceList.add(new String[]{"botName", botName});
appendReplacedKeyword("WHO_YOU_ARE", replaceList);
keywordMap.put("onlineModeTalkers", onlineModeTalkers); keywordMap.put("onlineModeTalkers", onlineModeTalkers);
varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString()); varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString());
//System.out.println("onlineModeTalkers" + varInitialMap.get("onlineModeTalkers"));
conditionDescription.put("onlineModeTalkers", "所有在线npc"); conditionDescription.put("onlineModeTalkers", "所有在线npc");
//同时识别zainali和wenzainali
configTermText = new ConfigTermText(
"zainali::match-Include=" + keywordMap.get("WHERE_I_AM_zainali") + "," +
"wenzainali::match-Keyword=" + keywordMap.get("NPC_LOCATION_wenzainali").toString(), " ",
"match,return-0", "", "yaobuyao", "npc_query:queryLocationByConditionName:wenzainali"
);
ConfigTermText.activateCopy(configTermText, configTermTextList, "npc");
//根据根据NPC的名字查询地点 //根据根据NPC的名字查询地点
for (String conditionName : locationRelateConditions) { queryTypeConfigTermGenerate(keywordMap, "NPC_LOCATION", "npc", "queryLocationByConditionName");
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ",
"match,return-0", "", "yaobuyao", "npc_query:queryLocationByConditionName:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "npc");
//zainali 和wenzainali 都识别到时优先匹配wenzainali
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName) + "," +
"zainali::match-Keyword=" + keywordMap.get("map_zainali").toString(), " ",
"match,return-0", "", "yaobuyao", "npc_query:queryLocationByConditionName:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "npc");
//configTermList.add(configTerm);
}
//根据根据NPC名字和属性查询属性值 //根据根据NPC名字和属性查询属性值
for(String conditionName: attrRelateConditions){ queryTypeConfigTermGenerate(keywordMap, "NPC_ATTR", "npc", "queryAttrByNPCName");
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ",
"match,return-0", "", "yaobuyao",
"npc_query:queryAttrByNPCName:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "npc");
}
//根据根据NPC类别和地点属性查询所有NPC实例 //根据根据NPC类别和地点属性查询所有NPC实例
for (String conditionName : classRelateConditions) {
queryTypeConfigTermGenerate(keywordMap, "AOURND_NPC_CLASS", "npc", "queryAroundNpcByClassName");
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ",
"match,return-0", "", "yaobuyao",
"npc_query:queryAroundNpcByClassName:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "npc");
//configTermList.add(configTerm);
}
//根据类名查询周围所有实例 //根据类名查询周围所有实例
for (String conditionName : findRelateConditions) {
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName).toString(), " ",
"match,return-0",
"",
" ",
"npc_query:queryFindNPCWay:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "npc");
}
//查询说话的人 queryTypeConfigTermGenerate(keywordMap, "HOW_FIND_NPC", "npc", "queryFindNPCWay");
for (String conditionName : talkerRelateConditions) {
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("talker_" + conditionName).toString().replace("botname", botName), " ",
"match,return-0",
"",
" ",
"npc_query:queryLastTalker:"
);
ConfigTerm.activateCopy(configTerm, configTermList, "npc");
}
//查询说话的人
//WHO_YOU_ARE
queryTypeConfigTermGenerate(keywordMap, "WHO_YOU_ARE", "npc", "queryLastTalker");
}catch (Exception e){ }catch (Exception e){
operationStatus = 0; operationStatus = 0;
...@@ -197,5 +162,9 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -197,5 +162,9 @@ public class CharacterConstructor extends ElementConstructor {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
} }
} }
...@@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; ...@@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
...@@ -19,8 +19,7 @@ public class ElementConstructor { ...@@ -19,8 +19,7 @@ public class ElementConstructor {
Map<String, StringBuffer> keywordMap = null; Map<String, StringBuffer> keywordMap = null;
SqlHelper helper = null; SqlHelper helper = null;
HashSet<String> exceptRelation = null; HashSet<String> exceptRelation = null;
ConfigTerm configTerm = null; ConfigTermText configTermText = null;
String CHITCHAT_URL = "http:192.168.1.178:1111/test";
String botAccount; String botAccount;
...@@ -29,7 +28,7 @@ public class ElementConstructor { ...@@ -29,7 +28,7 @@ public class ElementConstructor {
List<JSONObject> configDataList = new ArrayList<JSONObject>(); List<JSONObject> configDataList = new ArrayList<JSONObject>();
List<ConfigTerm> configTermList = new ArrayList<ConfigTerm>(); List<ConfigTermText> configTermTextList = new ArrayList<ConfigTermText>();
StringBuffer configText = new StringBuffer(); StringBuffer configText = new StringBuffer();
Map<String, String> varInitialMap = new HashMap<String, String>(); Map<String, String> varInitialMap = new HashMap<String, String>();
Map<String, String> conditionDescription = new HashMap<String, String>(); Map<String, String> conditionDescription = new HashMap<String, String>();
...@@ -46,8 +45,8 @@ public class ElementConstructor { ...@@ -46,8 +45,8 @@ public class ElementConstructor {
public void construct(JSONObject gameElements, UserInfo userinfo) { } public void construct(JSONObject gameElements, UserInfo userinfo) { }
public List<ConfigTerm> getConfigTermList() { public List<ConfigTermText> getConfigTermTextList() {
return configTermList; return configTermTextList;
} }
public Map<String, String> getConditionDescription() { public Map<String, String> getConditionDescription() {
...@@ -66,16 +65,19 @@ public class ElementConstructor { ...@@ -66,16 +65,19 @@ public class ElementConstructor {
return configText.toString(); return configText.toString();
} }
//生成完整的后台配置文件
public void generateConfigText(List<Integer> idList) { public void generateConfigText(List<Integer> idList) {
int id, length = idList.size(); int id, length = idList.size();
String varValue; String varValue;
ConfigTerm configTerm = null; ConfigTermText configTermText = null;
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
configTerm = configTermList.get(i); configTermText = configTermTextList.get(i);
id = idList.get(i); id = idList.get(i);
configText.append(configTerm.toString() + id + "\n"); configText.append(configTermText.toString() + id + "\n");
} }
//变量
for (String varName : varInitialMap.keySet()) { for (String varName : varInitialMap.keySet()) {
varValue = varInitialMap.get(varName); varValue = varInitialMap.get(varName);
configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n"); configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n");
...@@ -83,6 +85,14 @@ public class ElementConstructor { ...@@ -83,6 +85,14 @@ public class ElementConstructor {
} }
/**
* 从生成的配置文件的获取哪些condition需要哪些关键词,然后用于生成condition
* @param config
* @param relationKeywords
* @param exceptRelation
* @param botName
*/
public void parseKeyword(JSONObject config, Map<String, HashSet<String>> relationKeywords, HashSet<String> exceptRelation, String botName){ public void parseKeyword(JSONObject config, Map<String, HashSet<String>> relationKeywords, HashSet<String> exceptRelation, String botName){
String conditionName, pair[]; String conditionName, pair[];
for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){ for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){
...@@ -92,11 +102,13 @@ public class ElementConstructor { ...@@ -92,11 +102,13 @@ public class ElementConstructor {
if(!exceptRelation.contains(conditionName)) { if(!exceptRelation.contains(conditionName)) {
//初始化
if(!relationKeywords.containsKey(conditionName + "_head")) { if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>()); relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>()); relationKeywords.put(conditionName + "_tail", new HashSet<String>());
} }
//visitorname和bot的替换
premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname"));
for (String keyword : ((String) premise.get("keywords")).split("\\+")) { for (String keyword : ((String) premise.get("keywords")).split("\\+")) {
...@@ -106,6 +118,7 @@ public class ElementConstructor { ...@@ -106,6 +118,7 @@ public class ElementConstructor {
} else if(keyword.contains(":")){ } else if(keyword.contains(":")){
//有些配置条目要求三元组两边的值都匹配,需要把两边的值分别加入题头和值域
pair = keyword.split(":",2); pair = keyword.split(":",2);
if(pair[1].equals("")) if(pair[1].equals(""))
...@@ -133,6 +146,7 @@ public class ElementConstructor { ...@@ -133,6 +146,7 @@ public class ElementConstructor {
if(!exceptRelation.contains(conditionName)) { if(!exceptRelation.contains(conditionName)) {
if(!relationKeywords.containsKey(conditionName + "_head")) { if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>()); relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>()); relationKeywords.put(conditionName + "_tail", new HashSet<String>());
...@@ -189,4 +203,57 @@ public class ElementConstructor { ...@@ -189,4 +203,57 @@ public class ElementConstructor {
} }
} }
public void queryTypeConfigTermGenerate(Map<String, StringBuffer> keywordMap, String intent, String module, String queryMethod){
String conditionKeywords = "";
String conditionNameList[] = keywordMap.get(intent).toString().split(",");
for (String conditionName : conditionNameList) {
conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString();
configTermText = new ConfigTermText(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0",
"",
" ",
module + "_query:" + queryMethod + ":" + conditionName
);
//ConfigTermText.activateCopy(configTermText, configTermTextList, module);
//查询文本可能是被无条件剧情激活的,这时候的回答应该包含无条件剧情的剧情文本,这个文本存放在临时变量reply 里面
configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}");
configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}");
configTermText.setConfigName(module, true);
configTermTextList.add(configTermText);
}
}
/**
* 将condition的关键词复制一份,然后清空原来关键词
* @param intent
*/
public void copyPattern(String intent){
for(String conditionName:keywordMap.get(intent).toString().split(",")){
keywordMap.put(intent + "_" + conditionName + "_" + "pattern", new StringBuffer(keywordMap.get(intent + "_" + conditionName)));
keywordMap.get(intent + "_" + conditionName).setLength(0);
}
}
public void appendReplacedKeyword(String intent, List<String[]> replaceList){
String pattern, replaceText;
for(String conditionName:keywordMap.get(intent).toString().split(",")){
pattern = keywordMap.get( intent + "_" + conditionName + "_pattern").toString();
for(String[] replacePair: replaceList){
pattern = pattern.replace(replacePair[0], replacePair[1]);
}
keywordMap.get(intent + "_" + conditionName).append(pattern);
}
}
} }
...@@ -8,6 +8,8 @@ import java.util.HashSet; ...@@ -8,6 +8,8 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import static com.qiwu.chatbotbackend.Config.Config.CC_URL;
public class GlobalVariableConstructor extends ElementConstructor { public class GlobalVariableConstructor extends ElementConstructor {
public GlobalVariableConstructor(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) { public GlobalVariableConstructor(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) {
...@@ -40,7 +42,7 @@ public class GlobalVariableConstructor extends ElementConstructor { ...@@ -40,7 +42,7 @@ public class GlobalVariableConstructor extends ElementConstructor {
varInitialMap.put("botType", "game"); varInitialMap.put("botType", "game");
varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList")); varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList"));
varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText")); varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText"));
varInitialMap.put("CC_URL", keywordMap.get("CC_URL").toString()); varInitialMap.put("CC_URL", CC_URL);
JSONObject script = gameElements.getJSONObject("speechcraft"); JSONObject script = gameElements.getJSONObject("speechcraft");
......
...@@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; ...@@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
...@@ -26,7 +26,7 @@ public class ItemConstructor extends ElementConstructor { ...@@ -26,7 +26,7 @@ public class ItemConstructor extends ElementConstructor {
public void construct(JSONObject gameElements, UserInfo userinfo) { public void construct(JSONObject gameElements, UserInfo userinfo) {
try { try {
String pattern1 = keywordMap.get("item_location_pattern").toString(); String pattern;
String category, name, className, description, attrValue; String category, name, className, description, attrValue;
JSONArray goods = gameElements.getJSONArray("goods"); JSONArray goods = gameElements.getJSONArray("goods");
Map<String, String> attribute = null; Map<String, String> attribute = null;
...@@ -34,34 +34,19 @@ public class ItemConstructor extends ElementConstructor { ...@@ -34,34 +34,19 @@ public class ItemConstructor extends ElementConstructor {
HashSet<String> classSet = new HashSet<String>(); HashSet<String> classSet = new HashSet<String>();
keywordMap.putIfAbsent("item_wenzainali", new StringBuffer()); copyPattern("HOW_FIND_ITEM");
keywordMap.putIfAbsent("item_shishenme", new StringBuffer()); copyPattern("ITEM_LOCATION");
keywordMap.putIfAbsent("item_know_exist_what", new StringBuffer()); copyPattern("AROUND_ITEM_CLASS");
keywordMap.putIfAbsent("item_nums", new StringBuffer()); copyPattern("ITEM_ATTR");
keywordMap.putIfAbsent("item_want_know_zenmezuo", new StringBuffer());
List<String[]> replaceList = new ArrayList<String[]>();
//与物品属性查询相关的所有condition
String attrRelateConditions[] = {"nums", "shishenme"};
String ownRelateConditions[] = {"rencheng"};
//与物品类查询相关的所有condition
String classRelateConditions[] = {"know_exist_what" };
String locationRelateConditions[] = {"wenzainali"};
//如何找到×××××× ,这样的condition
String findRelateConditions[] = {"want_know_zenmezuo"};
String findPattern = keywordMap.get("find_pattern").toString();
StringBuffer classKeywords = new StringBuffer();
String classPattern = keywordMap.get("item_class_pattern").toString();
for (JSONObject good : goods.toJavaList(JSONObject.class)) { for (JSONObject good : goods.toJavaList(JSONObject.class)) {
name = (String) good.get("name"); name = (String) good.get("name");
replaceList.clear();
replaceList.add(new String[]{"name", name});
List<String> nameList = new ArrayList<String>(); List<String> nameList = new ArrayList<String>();
nameList.add(name); nameList.add(name);
...@@ -69,16 +54,18 @@ public class ItemConstructor extends ElementConstructor { ...@@ -69,16 +54,18 @@ public class ItemConstructor extends ElementConstructor {
className = (String) good.get("class"); className = (String) good.get("class");
appendPOS(POS, name, "名词"); appendPOS(POS, name, "名词");
appendPOS(POS, className, "名词"); appendPOS(POS, className, "名词");
keywordMap.get("item_want_know_zenmezuo").append(findPattern.replace("name", name));
keywordMap.get("item_" + locationRelateConditions[0]).append(pattern1.replace("name", name)); appendReplacedKeyword("ITEM_LOCATION", replaceList);
appendReplacedKeyword("HOW_FIND_ITEM", replaceList);
if(good.containsKey("nickname")){ if(good.containsKey("nickname")){
for(String nickname:JSONArray.parseArray(good.getJSONArray("nickname").toJSONString(), String.class)){ for(String nickname:JSONArray.parseArray(good.getJSONArray("nickname").toJSONString(), String.class)){
if(!nickname.equals("")) { if(!nickname.equals("")) {
appendPOS(POS, nickname, "名词"); appendPOS(POS, nickname, "名词");
nameList.add(nickname); nameList.add(nickname);
keywordMap.get("item_want_know_zenmezuo").append(findPattern.replace("name", nickname)); replaceList.get(0)[1] = nickname;
keywordMap.get("item_" + locationRelateConditions[0]).append(pattern1.replace("name", nickname)); appendReplacedKeyword("ITEM_LOCATION", replaceList);
appendReplacedKeyword("HOW_FIND_ITEM", replaceList);
} }
} }
} }
...@@ -86,97 +73,52 @@ public class ItemConstructor extends ElementConstructor { ...@@ -86,97 +73,52 @@ public class ItemConstructor extends ElementConstructor {
//添加类名称 //添加类名称
if (!classSet.contains(className)) { if (!classSet.contains(className)) {
classSet.add(className); classSet.add(className);
keywordMap.get("item_know_exist_what").append(classPattern.replace("name", className)); replaceList.get(0)[1] = className;
appendReplacedKeyword("AROUND_ITEM_CLASS", replaceList);
} }
attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class); attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class);
for(String attrName: attribute.keySet()){
replaceList.get(0)[1] = name;
replaceList.add(new String[]{"attrName", ""});
for(String attrName: attribute.keySet()){
replaceList.get(1)[1] = attrName;
appendPOS(POS, attrName, "名词"); appendPOS(POS, attrName, "名词");
for(String itemName:nameList) {
for (String condition : attrRelateConditions) { // for(String itemName:nameList) {
keywordMap.get("item_" + condition).append("+" + itemName + ":" + attrName); // for(String conditionName:keywordMap.get("ITEM_ATTR").toString().split(",")){
} // //pattern = keywordMap.get("NPC_ATTR_" + conditionName + "_pattern").toString();
} // keywordMap.get("ITEM_ATTR_" + conditionName).append("+").append(itemName).append(":").append(attrName);
// }
// }
appendReplacedKeyword("ITEM_ATTR", replaceList);
} }
} }
//与地点查询相关的condition configTermText = new ConfigTermText(
for(String conditionName: locationRelateConditions){ "zainali::match-Include=" + keywordMap.get("WHERE_I_AM_zainali") + "," +
configTerm = new ConfigTerm( "wenzainali::match-Keyword=" + keywordMap.get("ITEM_LOCATION_wenzainali").toString(), " ",
conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString() + "," + "match,return-0", "", "yaobuyao", "goods_query:queryLocationByConditionName:wenzainali"
"zainali::match-Keyword=" + keywordMap.get("map_zainali").toString(), " ", );
"match,return-0", ConfigTermText.activateCopy(configTermText, configTermTextList, "item");
"",
" ",
"goods_query:queryLocationByConditionName:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "item");
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ",
"match,return-0",
"",
" ",
"goods_query:queryLocationByConditionName:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "item");
}
//根据根据物品名字和属性查询属性值 queryTypeConfigTermGenerate(keywordMap, "ITEM_LOCATION", "goods", "queryLocationByConditionName");
for (String conditionName : attrRelateConditions) {
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ",
"match,return-0",
"",
" ",
"goods_query:queryAttrByGoodsName:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "item");
}
//根据根据物品名字和属性查询属性值
queryTypeConfigTermGenerate(keywordMap, "ITEM_ATTR", "goods", "queryAttrByGoodsName");
//根据类名查询周围所有实例 //根据类名查询周围所有实例
for (String conditionName : attrRelateConditions) { queryTypeConfigTermGenerate(keywordMap, "AROUND_ITEM_CLASS", "goods", "queryAroundGoodsByClassName");
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + classKeywords, " ",
"match,return-0",
"",
" ",
"goods_query:queryAroundGoodsByClassName:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "item");
}
//根据类名查询周围所有实例 //根据类名查询周围所有实例
for (String conditionName : ownRelateConditions) { queryTypeConfigTermGenerate(keywordMap, "WHAT_ITEM_I_HAVE", "goods", "queryPlayerItems");
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ",
"match,return-0",
"",
" ",
"goods_query:queryPlayerItems:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "item");
}
//根据类名查询周围所有实例 queryTypeConfigTermGenerate(keywordMap, "HOW_FIND_ITEM", "goods", "queryFindItemWay");
for (String conditionName : findRelateConditions) {
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ",
"match,return-0",
"",
" ",
"goods_query:queryFindItemWay:" + conditionName
);
ConfigTerm.activateCopy(configTerm, configTermList, "item");
}
} catch(Exception e){ } catch(Exception e){
operationStatus = 0; operationStatus = 0;
......
...@@ -3,13 +3,13 @@ package com.qiwu.chatbotbackend.gameDesign; ...@@ -3,13 +3,13 @@ package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.Premise; import com.qiwu.chatbotbackend.entity.Premise;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.*; import static com.qiwu.chatbotbackend.Config.Config.*;
public class ListeningConstructor extends ElementConstructor{ public class ListeningConstructor extends ElementConstructor{
...@@ -30,7 +30,7 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -30,7 +30,7 @@ public class ListeningConstructor extends ElementConstructor{
} }
public static void cc(String botAccount, JSONObject gameELments, HashMap<String, JSONObject> plotIndex, List<ConfigTerm> configTermList){ public static void cc(String botAccount, JSONObject gameELments, HashMap<String, JSONObject> plotIndex, List<ConfigTermText> configTermTextList){
int size = 0; int size = 0;
String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority; String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority;
String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep; String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep;
...@@ -70,7 +70,7 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -70,7 +70,7 @@ public class ListeningConstructor extends ElementConstructor{
if(nextCondition == null || nextCondition.equals("")){ if(nextCondition == null || nextCondition.equals("")){
nextCondition = "yaobuyao"; nextCondition = DEFAULT_CONDITION;
} }
if(autoJump){ if(autoJump){
...@@ -108,7 +108,7 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -108,7 +108,7 @@ public class ListeningConstructor extends ElementConstructor{
feature = "match,return-0"; feature = "match,return-0";
} }
ConfigTerm configTerm = new ConfigTerm( ConfigTermText configTermText = new ConfigTermText(
curPremiseList, curPremiseList,
hisPremiseList, hisPremiseList,
updateKnowledge, updateKnowledge,
...@@ -116,7 +116,7 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -116,7 +116,7 @@ public class ListeningConstructor extends ElementConstructor{
); );
System.out.println("生成:" + curPremiseList.get(0)); System.out.println("生成:" + curPremiseList.get(0));
configTermList.add(configTerm); configTermTextList.add(configTermText);
} }
} }
......
...@@ -3,14 +3,17 @@ package com.qiwu.chatbotbackend.gameDesign; ...@@ -3,14 +3,17 @@ package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.Config.Config.TASK_CONDITION;
import static com.qiwu.chatbotbackend.Config.Config.TASK_LINE;
import static com.qiwu.chatbotbackend.Config.Config.TASK_REPLY;
public class MapConstructor extends ElementConstructor { public class MapConstructor extends ElementConstructor {
String nickname = "qiwu";
int[][] matrix; int[][] matrix;
int locationNum; int locationNum;
HashMap<Integer, JSONObject> id2j = new HashMap<Integer, JSONObject>(); HashMap<Integer, JSONObject> id2j = new HashMap<Integer, JSONObject>();
...@@ -50,7 +53,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -50,7 +53,7 @@ public class MapConstructor extends ElementConstructor {
keywordMap.get("site_list").append("+").append(locationName); keywordMap.get("site_list").append("+").append(locationName);
taskLineName = String.format(PlotConstructor2.TASK_LINE, locationName); taskLineName = String.format(TASK_LINE, locationName);
if (!varInitialMap.containsKey(taskLineName)) { if (!varInitialMap.containsKey(taskLineName)) {
...@@ -109,56 +112,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -109,56 +112,7 @@ public class MapConstructor extends ElementConstructor {
Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); Map<String, String> question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class);
script = JSONObject.toJavaObject(gameElements.getJSONObject("speechcraft"), Map.class); script = JSONObject.toJavaObject(gameElements.getJSONObject("speechcraft"), Map.class);
if(!script.containsKey("PATH_AT"))
script.put("PATH_AT", "你已经在[地点名]了");
if(!script.containsKey("WHERE_I_AM"))
script.put("WHERE_I_AM", "在[地点名]");
if(!script.containsKey("PATH_ADJOINT"))
script.put("PATH_ADJOINT", "就在附近哦");
if(!script.containsKey("PATH_EXIST"))
script.put("PATH_EXIST", "通过[途径]可以到达[目的地]");
if(!script.containsKey("PATH_NOT_EXIST"))
script.put("PATH_NOT_EXIST", "不可到达");
if(!script.containsKey("CAN_GO_SITES"))
script.put("CAN_GO_SITES", "你可以去[可去列表]");
if(!script.containsKey("CAN_GO_NOWHERE"))
script.put("CAN_GO_NOWHERE", "没什么地方可去的,继续玩吧");
if(!script.containsKey("SITE_NOT_ACTIVE"))
script.put("SITE_NOT_ACTIVE", "你来到了[地点名]");
if(!script.containsKey("SITE_NOT_ADJOINT"))
script.put("SITE_NOT_ADJOINT", "通过[途径]可以到达[目的地]");
if(!script.containsKey("AROUND_PEOPLE"))
script.put("AROUND_PEOPLE", "周围有[人物列表]");
if(!script.containsKey("AROUND_ITEMS"))
script.put("AROUND_ITEMS", "周围有[物品列表]");
if(!script.containsKey("AROUND_THINGS"))
script.put("AROUND_THINGS", "周围有[人物物品列表]");
if(!script.containsKey("FIND_ITEM_LOCATION"))
script.put("FIND_ITEM_LOCATION", "[物品名]在[地点]");
if(!script.containsKey("FIND_NPC_LOCATION"))
script.put("FIND_NPC_LOCATION", "[人名]在[地点]");
if(!script.containsKey("AROUND_PLACE"))
script.put("AROUND_PLACE", "周围有[地点列表]");
if(!script.containsKey("FIND_ITEM_WAY"))
script.put("FIND_ITEM_WAY", "[人名]在[地点]");
if(!script.containsKey("FIND_NPC_WAY"))
script.put("FIND_NPC_WAY", "[物品名]在[地点]");
if(!script.containsKey("GET_ITEM_ATTR"))
script.put("GET_ITEM_ATTR", "[物品名]的[属性名]是[属性值]");
if(!script.containsKey("WE_HAVE"))
script.put("WE_HAVE", "我们有[物品列表]");
if(!script.containsKey("GET_NPC_ATTR"))
script.put("GET_NPC_ATTR", "[人名]的[属性名]是[属性值]");
if(!script.containsKey("INNER_PEOPLE"))
script.put("INNER_PEOPLE", "里面有[人物列表]");
if(!script.containsKey("WHO_YOU_ARE"))
script.put("WHO_YOU_ARE", "我是[人名]");
if(!script.containsKey("TASK_DESCRIPTION"))
script.put("TASK_DESCRIPTION", "我们的任务是[任务描述]");
if(!script.containsKey("ITEM_IS_YOURS"))
script.put("ITEM_IS_YOUR", "在你身上呢");
if(!script.containsKey("FIND_ITEM_OWNER"))
script.put("FIND_INTEM_OWNER", "[物品名]在[人名]那");
...@@ -173,20 +127,24 @@ public class MapConstructor extends ElementConstructor { ...@@ -173,20 +127,24 @@ public class MapConstructor extends ElementConstructor {
constructGreph(locations); constructGreph(locations);
//用弗洛伊德算法求最短路径 //用弗洛伊德算法求最短路径
Floyd floyd = new Floyd(); //Floyd floyd = new Floyd();
floyd.findShortestPath(matrix, locationNum); //floyd.findShortestPath(matrix, locationNum);
floyd.printPath(matrix, locationNum); //floyd.printPath(matrix, locationNum);
generateWantToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); generateWantToThere(gameElements, keywordMap);
generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); generateHowToThere(gameElements, keywordMap);
generateWhereIam(gameElements, userName, keywordMap);
generateHowToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); //查询类型配置条目的生成
generateSurroundingItem(keywordMap); queryTypeConfigTermGenerate(keywordMap, "WHERE_I_AM", "map", "queryWhereIam");
generateSurroundingPeople(keywordMap); queryTypeConfigTermGenerate(keywordMap, "WHERE_CAN_I_GO", "map", "queryCanGoBySite");
generateSurroundThings(keywordMap); queryTypeConfigTermGenerate(keywordMap, "AROUND_NPC", "map", "queryAroundNpcBySite");
generateSurroundPlace(keywordMap); queryTypeConfigTermGenerate(keywordMap, "AROUND_ITEM", "map", "queryAroundGoodsBySite");
generateWeHave(keywordMap); queryTypeConfigTermGenerate(keywordMap, "AROUND_THINGS", "map", "queryAroundAllBySite");
generateInnerPeople(keywordMap);
generateTaskDescription(keywordMap); queryTypeConfigTermGenerate(keywordMap, "AROUND_PLACE", "map", "queryAroundPlace");
queryTypeConfigTermGenerate(keywordMap, "WHO_IN_THERE", "map", "queryInnerNpcBySite");
queryTypeConfigTermGenerate(keywordMap, "TASK_IS_WHAT", "map", "queryTaskDescription");
queryTypeConfigTermGenerate(keywordMap, "WHAT_THINGS_IN_LOCATION", "map", "queryItemsInPlace");
} catch(Exception e){ } catch(Exception e){
...@@ -198,129 +156,107 @@ public class MapConstructor extends ElementConstructor { ...@@ -198,129 +156,107 @@ public class MapConstructor extends ElementConstructor {
} }
/**
* 生成‘我在哪里’所需要的配置文件
*/
public void generateWhereIam(JSONObject gameElements, String botAccount, Map<String, StringBuffer> keywordMap) {
String conditionNameList[] = {"zainali", "wenzainali"};
String conditionKeywords = "";
for(String condition:conditionNameList) {
conditionKeywords = keywordMap.get("map_" + condition).toString();
configTerm = new ConfigTerm(
condition + "::match-Include=" + conditionKeywords, " ",
"match", "", "yaobuyao",
"map_query:queryWhereIam:"
);
configTerm.setNextStepStatus("return-0");
configTerm.setAuxiliaryPriority("1");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
}
}
/** /**
* 生成‘怎么去哪里’所需要的配置文件 * 生成‘怎么去哪里’所需要的配置文件
*/ */
public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map<String, StringBuffer> keywordMap) { public void generateHowToThere(JSONObject gameElements, Map<String, StringBuffer> keywordMap) {
String conditionName = "want_know_zenmezuo"; //String conditionName = "want_know_zenmezuo";
String intent = "HOW_TO_THERE", placeA, keywordPattern, gotoSite;
String conditionNameList[] = keywordMap.get(intent).toString().split(",");
StringBuffer placeKeywords = new StringBuffer(); StringBuffer placeKeywords = new StringBuffer();
String nameSet; String nameSet;
for (int i = 0; i < locationNum; i++) { for(String conditionName:conditionNameList) {
nameSet = (String) locations.getJSONObject(i).get("nameSet"); placeKeywords.setLength(0);
placeKeywords.append("+").append(nameSet);
}
keywordPattern = keywordMap.get(intent + "_" + conditionName).toString();
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + placeKeywords
+ ",isNeighbour:"+ conditionName + "::match-Include=0",
" ",
"match,return-0",
"",
" ",
"map_query:queryPathAt:"
);
configTerm.setNextStepStatus("return-0");
configTerm.setAuxiliaryPriority("1");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + placeKeywords
+ ",isNeighbour:"+ conditionName + "::match-Include=1+3+4",
" " ,
"match,return-0",
"",
" ",
"map_query:queryPathAdjoin:"
);
configTerm.setNextStepStatus("return-0");
configTerm.setAuxiliaryPriority("1");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
//提取关键词
//conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString();
for (int i = 0; i < locationNum; i++) {
placeA = (String) locations.getJSONObject(i).get("name");
gotoSite = keywordPattern.replace("name", placeA);
//toAllSiteskeywords.append(gotoSite);
//toSitekeywords.append(gotoSite);
placeKeywords.append(gotoSite);
for (String nickname : name2nickname.get(placeA)) {
gotoSite = keywordPattern.replace("name", nickname);
placeKeywords.append(gotoSite);
//toSitekeywords.append(gotoSite);
}
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + placeKeywords
+ ",isNeighbour:"+ conditionName + "::match-Include=2",
" " ,
"match,return-0",
"",
" ",
"map_query:queryHowToPathBySite:" + conditionName
);
configTerm.setNextStepStatus("return-0");
configTerm.setAuxiliaryPriority("1");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
//nameSet = (String) locations.getJSONObject(i).get("nameSet");
//placeKeywords.append("+").append(nameSet);
}
} configTermText = new ConfigTermText(
conditionName + "::match-Include=" + placeKeywords
+ ",isNeighbour:" + conditionName + "::match-Include=0",
" ",
"match,return-0",
"",
" ",
"map_query:queryPathAt:"
);
configTermText.setNextStepStatus("return-0");
configTermText.setAuxiliaryPriority("1");
ConfigTermText.activateCopy(configTermText, configTermTextList, "map");
/** configTermText = new ConfigTermText(
* 生成‘我能去哪里’所需要的配置文件 conditionName + "::match-Include=" + placeKeywords
*/ + ",isNeighbour:" + conditionName + "::match-Include=1+3+4",
public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map<String, StringBuffer> keywordMap) { " ",
String conditionName = "choose_gowhere"; "match,return-0",
String conditionKeywords = keywordMap.get("map_" + conditionName).toString(); "",
" ",
"map_query:queryPathAdjoin:"
);
configTermText.setNextStepStatus("return-0");
configTermText.setAuxiliaryPriority("1");
ConfigTermText.activateCopy(configTermText, configTermTextList, "map");
String placeA, placeB, pathNode;
configTermText = new ConfigTermText(
conditionName + "::match-Include=" + placeKeywords
+ ",isNeighbour:" + conditionName + "::match-Include=2",
" ",
"match,return-0",
"",
" ",
"map_query:queryHowToPathBySite:" + conditionName
);
configTermText.setNextStepStatus("return-0");
configTermText.setAuxiliaryPriority("1");
ConfigTermText.activateCopy(configTermText, configTermTextList, "map");
}
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "", " ",
"map_query:queryCanGoBySite:"
);
configTerm.setNextStepStatus("return-0");
configTerm.setAuxiliaryPriority("1");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
} }
/** /**
* 生成‘我要去那里’所需要的配置文件 * 生成‘我要去那里’所需要的配置文件
*/ */
public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map<String, StringBuffer> keywordMap) { public void generateWantToThere(JSONObject gameElements, Map<String, StringBuffer> keywordMap) {
String placeA, placeB, descriptionB, text, pathNode, lastTaskCondition, lastTaskReply, taskLine; String placeA, lastTaskCondition, lastTaskReply, taskLine;
String conditionName = "yaobuyao"; String intent = "GO_TO", keywordPattern;
String conditionKeywords = "地点"; String conditionName = keywordMap.get(intent).toString().split(",")[0];
String start = (String) gameElements.get("start");
String placeKeywords; keywordPattern = keywordMap.get(intent + "_" + conditionName).toString();
//包含去xx的所有地点的关键词集合 //包含去xx的所有地点的关键词集合
StringBuffer toAllSiteskeywords = new StringBuffer(); StringBuffer toAllSiteskeywords = new StringBuffer();
...@@ -329,30 +265,29 @@ public class MapConstructor extends ElementConstructor { ...@@ -329,30 +265,29 @@ public class MapConstructor extends ElementConstructor {
StringBuffer toSitekeywords = new StringBuffer(); StringBuffer toSitekeywords = new StringBuffer();
String goRelateConditions[] = {"yaobuyao"}; String gotoSite = "";
String gotoMapptern = keywordMap.get("map_" + goRelateConditions[0]).toString(), gotoSite = "";
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
toSitekeywords.setLength(0); toSitekeywords.setLength(0);
placeA = (String) locations.getJSONObject(i).get("name"); placeA = (String) locations.getJSONObject(i).get("name");
gotoSite = gotoMapptern.replace("name", placeA); gotoSite = keywordPattern.replace("name", placeA);
toAllSiteskeywords.append(gotoSite); toAllSiteskeywords.append(gotoSite);
toSitekeywords.append(gotoSite); toSitekeywords.append(gotoSite);
for (String nickname : name2nickname.get(placeA)) { for (String nickname : name2nickname.get(placeA)) {
gotoSite = gotoMapptern.replace("name", nickname); gotoSite = keywordPattern.replace("name", nickname);
toAllSiteskeywords.append(gotoSite); toAllSiteskeywords.append(gotoSite);
toSitekeywords.append(gotoSite); toSitekeywords.append(gotoSite);
} }
lastTaskCondition = String.format(PlotConstructor2.TASK_CONDITION, placeA); lastTaskCondition = String.format(TASK_CONDITION, placeA);
lastTaskReply = String.format(PlotConstructor2.TASK_REPLY, placeA); lastTaskReply = String.format(TASK_REPLY, placeA);
taskLine = String.format(PlotConstructor2.TASK_LINE, placeA); taskLine = String.format(TASK_LINE, placeA);
//地点任务和地点回答的初始化 //地点任务和地点回答的初始化
if (!varInitialMap.containsKey(lastTaskCondition)) { if (!varInitialMap.containsKey(lastTaskCondition)) {
varInitialMap.put(lastTaskCondition, goRelateConditions[0]); varInitialMap.put(lastTaskCondition, conditionName);
varInitialMap.put(lastTaskReply, script.get("SITE_NOT_ACTIVE").replace("[地点名]", placeA)); varInitialMap.put(lastTaskReply, script.get("SITE_NOT_ACTIVE").replace("[地点名]", placeA));
conditionDescription.put(lastTaskCondition, lastTaskCondition); conditionDescription.put(lastTaskCondition, lastTaskCondition);
conditionDescription.put(lastTaskReply, lastTaskReply); conditionDescription.put(lastTaskReply, lastTaskReply);
...@@ -362,37 +297,39 @@ public class MapConstructor extends ElementConstructor { ...@@ -362,37 +297,39 @@ public class MapConstructor extends ElementConstructor {
/** /**
* 要去某个地方,并且该地点相邻或者可以直接到达 * 要去某个地方,并且该地点相邻或者可以直接到达
*/ */
conditionName = goRelateConditions[0]; configTermText = new ConfigTermText(
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + toSitekeywords + "," + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", conditionName + "::match-Include=" + toSitekeywords + "," + ",isNeighbour:" + conditionName + "::match-Include=1+3+4",
" ", " ",
"match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_" + placeA + "_*", "" "match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_" + placeA + "_*", ""
); );
configTerm.setConfigName("map", true); configTermText.setConfigName("map", true);
configTermList.add(configTerm); configTermTextList.add(configTermText);
//上一个配置文件激活时的默认选项 //上一个配置文件激活时的默认选项(兜底),上一条一定会激活下一条,下一条是没有条件的,如果没有找到其他可以激活的配置条目,则激活下一条
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA " ", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA
+ "-<-npc_update:updateFollowerLocation:" + placeA + "-<-game_step:var={" + taskLine + "-2}" + "-<-npc_update:updateFollowerLocation:" + placeA + "-<-game_step:var={" + taskLine + "-2}"
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("plot_" + placeA + "_doudi", false); configTermText.setConfigName("plot_" + placeA + "_doudi", false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTermList.add(configTerm); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText);
//上一个配置文件激活时的默认选项, 地点任务线未开启,则不更新game_step //上一个配置文件激活时的默认选项, 地点任务线未开启,则不更新game_step
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
lastTaskCondition + "::match-Include=null", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA lastTaskCondition + "::match-Include=null", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA
+ "-<-npc_update:updateFollowerLocation:" + placeA + "-<-npc_update:updateFollowerLocation:" + placeA
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("plot_" + placeA + "_doudi2", false); configTermText.setConfigName("plot_" + placeA + "_doudi2", false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTermList.add(configTerm); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText);
} }
...@@ -400,7 +337,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -400,7 +337,7 @@ public class MapConstructor extends ElementConstructor {
/** /**
* 要去的地方就在当前地点 * 要去的地方就在当前地点
*/ */
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
conditionName + "::match-Include=" + toAllSiteskeywords conditionName + "::match-Include=" + toAllSiteskeywords
+ ",isNeighbour:" + conditionName + "::match-Include=0", + ",isNeighbour:" + conditionName + "::match-Include=0",
" ", " ",
...@@ -409,14 +346,14 @@ public class MapConstructor extends ElementConstructor { ...@@ -409,14 +346,14 @@ public class MapConstructor extends ElementConstructor {
" ", " ",
"map_query:queryPathAt:" "map_query:queryPathAt:"
); );
configTerm.setConfigName("map", true); configTermText.setConfigName("map", true);
configTermList.add(configTerm); configTermTextList.add(configTermText);
/** /**
* 要去的地方要经过几个地点才能到达 * 要去的地方要经过几个地点才能到达
*/ */
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
conditionName + "::match-Include=" + toAllSiteskeywords conditionName + "::match-Include=" + toAllSiteskeywords
+ ",isNeighbour:" + conditionName + "::match-Include=2", + ",isNeighbour:" + conditionName + "::match-Include=2",
" ", " ",
...@@ -425,13 +362,13 @@ public class MapConstructor extends ElementConstructor { ...@@ -425,13 +362,13 @@ public class MapConstructor extends ElementConstructor {
" ", " ",
"map_query:queryToDoPathBySite:" + conditionName "map_query:queryToDoPathBySite:" + conditionName
); );
configTerm.setConfigName("map", true); configTermText.setConfigName("map", true);
configTermList.add(configTerm); configTermTextList.add(configTermText);
/** /**
* 要去的地方不可到达 * 要去的地方不可到达
*/ */
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
conditionName + "::match-Include=" + toAllSiteskeywords conditionName + "::match-Include=" + toAllSiteskeywords
+ ",isNeighbour:" + conditionName + "::match-Include=5", + ",isNeighbour:" + conditionName + "::match-Include=5",
" ", " ",
...@@ -440,152 +377,8 @@ public class MapConstructor extends ElementConstructor { ...@@ -440,152 +377,8 @@ public class MapConstructor extends ElementConstructor {
" ", " ",
"map_query:queryPathNotExist:" "map_query:queryPathNotExist:"
); );
configTerm.setConfigName("map", true); configTermText.setConfigName("map", true);
configTermList.add(configTerm); configTermTextList.add(configTermText);
}
/**
* 生成‘周围有什么人’所需要的配置文件
*/
public void generateSurroundingPeople(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what";
String conditionKeywords = keywordMap.get("people_" + conditionName).toString();
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "", "yaobuyao",
"map_query:queryAroundNpcBySite:"
);
ConfigTerm.activateCopy(configTerm, configTermList, "map");
}
/**
* 生成‘周围有什么物品’所需要的配置文件
*/
public void generateSurroundingItem(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what";
String conditionKeywords = keywordMap.get("item_" + conditionName).toString();
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "", "yaobuyao",
"map_query:queryAroundGoodsBySite:"
);
ConfigTerm.activateCopy(configTerm, configTermList, "map");
}
/**
* 生成‘周围有什么(包含人和物品)’所需要的配置文件
*/
public void generateSurroundThings(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what_mohu";
String conditionKeywords = keywordMap.get("things_" + conditionName).toString();
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "", "yaobuyao",
"map_query:queryAroundAllBySite:"
);
ConfigTerm.activateCopy(configTerm, configTermList, "map");
} }
/**
* 生成‘周围有什么地点’所需要的配置文件
*/
public void generateSurroundPlace(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what";
String conditionKeywords = keywordMap.get("place_" + conditionName).toString();
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "", " ",
"map_query:queryAroundPlace:"
);
configTerm.setNextStepStatus("return-0");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
}
/**
* 生成‘我们有什么’所需要的配置文件
*/
public void generateWeHave(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what_mohu";
String conditionKeywords = keywordMap.get("we_have_" + conditionName).toString();
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "", " ",
"goods_query:queryPlayerItems:"
);
configTerm.setNextStepStatus("return-0");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
}
/**
* 生成‘里面有什么人’所需要的配置文件
*/
public void generateInnerPeople(Map<String, StringBuffer> keywordMap){
//与里面有谁相关的condition
String innerNPCRelateConditions[] = {"shishui"};
keywordMap.putIfAbsent("inner_shishui", new StringBuffer());
String conditionName = "shishui";
String conditionKeywords = keywordMap.get("inner_" + conditionName).toString();
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "", " ",
"map_query:queryInnerNpcBySite:"
);
configTerm.setNextStepStatus("return-0");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
}
/**
* 生成‘我们的任务是什么’所需要的配置文件
*/
public void generateTaskDescription(Map<String, StringBuffer> keywordMap){
//与里面有谁相关的condition
String innerNPCRelateConditions[] = {};
keywordMap.putIfAbsent("task_shishenme", new StringBuffer());
String conditionName = "shishenme";
String conditionKeywords = keywordMap.get("task_" + conditionName).toString();
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "", " ",
"map_query:queryTaskDescription:"
);
configTerm.setNextStepStatus("return-0");
ConfigTerm.activateCopy(configTerm, configTermList, "map");
}
} }
\ No newline at end of file
...@@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; ...@@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.Premise; import com.qiwu.chatbotbackend.entity.Premise;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
...@@ -12,15 +12,11 @@ import java.util.*; ...@@ -12,15 +12,11 @@ import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.Config.Config.*;
public class PlotConstructor2 extends ElementConstructor {
public static String ASSISTANT = "globalVariable_智能助手"; public class PlotConstructor2 extends ElementConstructor {
public static String ASSISTANT_EMOTION = "正常";
public static String TASK_DESCRIPTION = "globalVariable_任务";
public static String TALKER_PATTERN = "【%s@%s】";
public static String GAME_STEP_FORMAT = "%s_plot_%s";
JSONArray plots = null; JSONArray plots = null;
HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>(); HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
...@@ -32,10 +28,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -32,10 +28,6 @@ public class PlotConstructor2 extends ElementConstructor {
return plotIndex; return plotIndex;
} }
public static String TASK_LINE = "任务线_%s进度";
public static String TASK_CONDITION = "任务线%s最后一个condition";
public static String TASK_REPLY = "任务线%s最后的回答";
public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) { public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) {
super(); super();
...@@ -62,7 +54,8 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -62,7 +54,8 @@ public class PlotConstructor2 extends ElementConstructor {
constructAdjList(plots); constructAdjList(plots);
if (plotIndex.containsKey(start)) { if (plotIndex.containsKey(start)) {
String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度"; //String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度";
String taskLineName = String.format(TASK_LINE, plotIndex.get(start).get("place"));
conditionDescription.put(taskLineName, taskLineName); conditionDescription.put(taskLineName, taskLineName);
if(jsonObject.get("firstUnknownText") == null) if(jsonObject.get("firstUnknownText") == null)
...@@ -72,24 +65,24 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -72,24 +65,24 @@ public class PlotConstructor2 extends ElementConstructor {
varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id"))); varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id")));
conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); conditionDescription.put("unknownText", UNKNOWN_TEXT_DESCRIPTION);
conditionDescription.put("game_step", "QA问答游戏进度"); conditionDescription.put("game_step", GAME_STEP_DESCRIPTION);
BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); BFSGenerate4(plotIndex.get(start), userinfo, jsonObject);
varInitialMap.put(start, "1"); varInitialMap.put(start, "1");
ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermList); ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermTextList);
} else { } else {
System.out.println("start剧情不存在"); System.out.println(START_PLOT_NOT_EXIST);
operationStatus = 0; operationStatus = 0;
message = "开始剧情不存在,请到剧情列表设置"; message = START_PLOT_NOT_EXIST;
return; return;
} }
} catch(Exception e){ } catch(Exception e){
operationStatus = 0; operationStatus = 0;
message = "剧情接口处理出现异常"; message = PLOT_GENERATION_ERROR;
e.printStackTrace(); e.printStackTrace();
return; return;
} }
...@@ -167,7 +160,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -167,7 +160,7 @@ public class PlotConstructor2 extends ElementConstructor {
public static void varSlotFilt(JSONObject plot, Map<String, StringBuffer> keywordMap){ public static void varSlotFilt(JSONObject plot, Map<String, StringBuffer> keywordMap){
String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本 String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本
System.out.println(plot.getString("id")); //System.out.println(plot.getString("id"));
Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN);
Matcher m = replacePattern.matcher(plot.getString("plotText")); Matcher m = replacePattern.matcher(plot.getString("plotText"));
while (m.find()) { while (m.find()) {
...@@ -193,7 +186,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -193,7 +186,7 @@ public class PlotConstructor2 extends ElementConstructor {
* @param userinfo * @param userinfo
*/ */
public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) {
String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = "yaobuyao", String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = DEFAULT_CONDITION,
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply;
String hint, gameStep, nextGameStep; String hint, gameStep, nextGameStep;
JSONObject node = null, branchNode = null; JSONObject node = null, branchNode = null;
...@@ -215,16 +208,16 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -215,16 +208,16 @@ public class PlotConstructor2 extends ElementConstructor {
if(root.get("conditionName") != null && !root.get("conditionName").equals("")) if(root.get("conditionName") != null && !root.get("conditionName").equals(""))
conditionName = (String)root.get("conditionName"); conditionName = (String)root.get("conditionName");
else{ else{
conditionName = "yaobuyao"; conditionName = DEFAULT_CONDITION;
root.put("conditionName", conditionName); root.put("conditionName", conditionName);
} }
String startPlace = ((String)root.get("place")).split("\\+")[0]; String startPlace = ((String)root.get("place")).split("\\+")[0];
String startTaskLine = String.format(PlotConstructor2.TASK_LINE, startPlace); String startTaskLine = String.format(TASK_LINE, startPlace);
String startTaskCondition = String.format(PlotConstructor2.TASK_CONDITION, startPlace); String startTaskCondition = String.format(TASK_CONDITION, startPlace);
String startTaskReply = String.format(PlotConstructor2.TASK_REPLY, startPlace); String startTaskReply = String.format(TASK_REPLY, startPlace);
varInitialMap.put("site", startPlace); varInitialMap.put("site", startPlace);
varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId)); varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId));
varInitialMap.put(startTaskCondition, ""); varInitialMap.put(startTaskCondition, "");
...@@ -239,7 +232,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -239,7 +232,7 @@ public class PlotConstructor2 extends ElementConstructor {
Queue<JSONObject> queue = new LinkedList<JSONObject>(); Queue<JSONObject> queue = new LinkedList<JSONObject>();
queue.add(root); queue.add(root);
System.out.println(root.toJSONString()); //System.out.println(root.toJSONString());
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
node = queue.remove(); node = queue.remove();
...@@ -249,8 +242,8 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -249,8 +242,8 @@ public class PlotConstructor2 extends ElementConstructor {
curAutoJump = node.getBoolean("autoJump"); curAutoJump = node.getBoolean("autoJump");
prevAutoJump = node.getBoolean("prevAutoJump"); prevAutoJump = node.getBoolean("prevAutoJump");
curUnknownText = (String) node.get("unknownText"); curUnknownText = (String) node.get("unknownText");
taskLineName = String.format(PlotConstructor2.TASK_LINE, location); taskLineName = String.format(TASK_LINE, location);
conditionDescription.put(id, "剧情" + id + "状态"); conditionDescription.put(id, String.format(PLOT_STATUS, id));
varInitialMap.put(id ,""); varInitialMap.put(id ,"");
//本任务线的最后一个condition和本任务线的最后一个回答 //本任务线的最后一个condition和本任务线的最后一个回答
...@@ -307,7 +300,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -307,7 +300,7 @@ public class PlotConstructor2 extends ElementConstructor {
//如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度
nextCondition = plotIndex.get(nextId).getString("conditionName"); nextCondition = plotIndex.get(nextId).getString("conditionName");
if(nextCondition.equals("")) if(nextCondition.equals(""))
nextCondition = "yaobuyao"; nextCondition = DEFAULT_CONDITION;
nextLocation = plotIndex.get(nextId).getString("place"); nextLocation = plotIndex.get(nextId).getString("place");
...@@ -357,7 +350,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -357,7 +350,7 @@ public class PlotConstructor2 extends ElementConstructor {
} }
System.out.println(id); //System.out.println(id);
appendFeature(extraFT, "match"); appendFeature(extraFT, "match");
//下一步为自动跳转且地点相同,则将回答放在plot_jump_text //下一步为自动跳转且地点相同,则将回答放在plot_jump_text
...@@ -433,7 +426,8 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -433,7 +426,8 @@ public class PlotConstructor2 extends ElementConstructor {
if(curUnknownText.equals("")) { if(curUnknownText.equals("")) {
//如果没有unknown,就提示他到下一个地点 //如果没有unknown,就提示他到下一个地点
hint = "请到" + nextLocation; hint = String.format(LOCATION_HINT, nextLocation);
//hint = "请到" + nextLocation;
//如果当前地点和下一步剧情地点不同,要提示 //如果当前地点和下一步剧情地点不同,要提示
}else { }else {
//如果有unknown,就提示unknown文本 //如果有unknown,就提示unknown文本
...@@ -484,14 +478,14 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -484,14 +478,14 @@ public class PlotConstructor2 extends ElementConstructor {
nextCondition = "plot_" + nextId; nextCondition = "plot_" + nextId;
} }
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
curPremiseList, curPremiseList,
historyPremiseList, historyPremiseList,
updateKnowledge, updateKnowledge,
"", extraHP.toString(), extraUK.toString(), "", extraHP.toString(), extraUK.toString(),
extraFT.toString(), reply, nextCondition, "1" extraFT.toString(), reply, nextCondition, "1"
); );
configTerm.setConfigName("plot_" + id, false); configTermText.setConfigName("plot_" + id, false);
//当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转 //当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转
...@@ -499,11 +493,11 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -499,11 +493,11 @@ public class PlotConstructor2 extends ElementConstructor {
Boolean activateFlag = false; Boolean activateFlag = false;
if(extraFT.indexOf("activate") != -1) if(extraFT.indexOf("activate") != -1)
activateFlag = true; activateFlag = true;
unconditionalPlotProcess(configTerm, nextCondition, activateFlag); unconditionalPlotProcess(configTermText, nextCondition, activateFlag);
} }
if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority"))
configTerm.setAuxiliaryPriority("3"); configTermText.setAuxiliaryPriority("3");
configTermList.add(configTerm); configTermTextList.add(configTermText);
...@@ -543,33 +537,36 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -543,33 +537,36 @@ public class PlotConstructor2 extends ElementConstructor {
* 4. 无论哪种情况都会跳下一步剧情 * 4. 无论哪种情况都会跳下一步剧情
*/ */
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match",
"{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}"
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("queryskip1",false); configTermText.setConfigName("queryskip1",false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTerm.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermList.add(configTerm); configTermTextList.add(configTermText);
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match",
"{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}"
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("queryskip2",false); configTermText.setConfigName("queryskip2",false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTerm.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermList.add(configTerm); configTermTextList.add(configTermText);
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" " ", "qa_status::match-Include=not_found", "match",
"{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}"
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("queryskip3",false); configTermText.setConfigName("queryskip3",false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTerm.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermList.add(configTerm); configTermTextList.add(configTermText);
...@@ -580,66 +577,70 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -580,66 +577,70 @@ public class PlotConstructor2 extends ElementConstructor {
*/ */
//处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0
configTerm = new ConfigTerm(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); configTermText = new ConfigTermText(" ", " ", "activate,post::gameQA(" + QA_URL + ")",
configTerm.setNextStepStatus("active"); "", "unknown4,unknown3,unknown2,unknown1,common_answer", "");
configTerm.setAuxiliaryPriority("0"); configTermText.setNextStepStatus("active");
configTermList.add(configTerm); configTermText.setAuxiliaryPriority("0");
configTermTextList.add(configTermText);
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" " ", "qa_status::match-Include=not_found", "match,return-0",
"{unknownText-2}", " ", ""
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("unknown1",false); configTermText.setConfigName("unknown1",false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTerm.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermList.add(configTerm); configTermTextList.add(configTermText);
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0",
"不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", UNKNOWN_TEXT,
" ", "" " ", ""
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("unknown2",false); configTermText.setConfigName("unknown2",false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTerm.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermList.add(configTerm); configTermTextList.add(configTermText);
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0",
"不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", UNKNOWN_TEXT,
" ", "" " ", ""
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("unknown3",false); configTermText.setConfigName("unknown3",false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTerm.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermList.add(configTerm); configTermTextList.add(configTermText);
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0",
"{unknownText-2}", " ", ""
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("unknown4",false); configTermText.setConfigName("unknown4",false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTerm.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermList.add(configTerm); configTermTextList.add(configTermText);
//由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
" ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "" ," ", "" " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0",
"" ," ", ""
); );
configTerm.setStatus("sleeping"); configTermText.setStatus("sleeping");
configTerm.setConfigName("common_answer",false); configTermText.setConfigName("common_answer",false);
configTerm.setjStatus(1); configTermText.setjStatus(1);
configTerm.setAuxiliaryPriority("0"); configTermText.setAuxiliaryPriority("0");
configTermList.add(configTerm); configTermTextList.add(configTermText);
//--------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------
...@@ -648,16 +649,24 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -648,16 +649,24 @@ public class PlotConstructor2 extends ElementConstructor {
* ---------------------------------------------------------------------------------------------------- * ----------------------------------------------------------------------------------------------------
* 用于存档 * 用于存档
*/ */
configTerm = new ConfigTerm( configTermText = new ConfigTermText(
"save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", "" "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup",
"{archiveOperation-2}" ," ", ""
); );
configTerm.setAuxiliaryPriority("4"); configTermText.setAuxiliaryPriority("4");
configTermList.add(configTerm); configTermTextList.add(configTermText);
} }
/**
* 新建一个剧情结点
* @param node
* @param id
* @param nextId
* @param nextUnknownText
*/
public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){
String condition = (String) node.get("conditionName"); String condition = (String) node.get("conditionName");
...@@ -684,6 +693,12 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -684,6 +693,12 @@ public class PlotConstructor2 extends ElementConstructor {
} }
/**
* 从配置文件中获取游戏开始时 游戏选择 的剧情, 即选择开始或者重新开始或者根据不同地点读档
* @param gameElements
* @param keywordMap
*/
void addGameStartPlot(JSONObject gameElements, Map<String, StringBuffer> keywordMap){ void addGameStartPlot(JSONObject gameElements, Map<String, StringBuffer> keywordMap){
...@@ -709,7 +724,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -709,7 +724,7 @@ public class PlotConstructor2 extends ElementConstructor {
gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart"));
gameElements.put("start", "start1"); gameElements.put("start", "start1");
gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); gameElements.put("firstUnknownText", GAME_START_HINT);
br.close(); br.close();
...@@ -725,22 +740,31 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -725,22 +740,31 @@ public class PlotConstructor2 extends ElementConstructor {
//如果是无条件剧情,那么需要跟着一个激活操作 //如果是无条件剧情,那么需要跟着一个激活操作
public void unconditionalPlotProcess(ConfigTerm configTerm, String nextCondition, Boolean activateFlag){ public void unconditionalPlotProcess(ConfigTermText configTermText, String nextCondition, Boolean activateFlag){
configTerm.setFeature(configTerm.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")"); configTermText.setFeature(configTermText.getFeature() + ",activate,post::gameQA(" + QA_URL + ")");
// //
//if() //if()
if(activateFlag){ if(activateFlag){
configTerm.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*"); configTermText.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*");
}else { }else {
configTerm.setNextStep("queryskip*,map*,item*,npc*"); configTermText.setNextStep("queryskip*,map*,item*,npc*");
} }
//将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中 //将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中,激活查询配置后,最后返回的condition应该是剧情指定的下一个condition
configTerm.setUpdateKnowledge(configTerm.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}");
configTerm.setNextStepStatus("active"); configTermText.setNextStepStatus("active");
} }
/**
* 在条件文本后面添加一个条件
* @param premiseStr
* @param conditionName
* @param cmpType
* @param operator
* @param value
*/
public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){
int strLen = premiseStr.length(); int strLen = premiseStr.length();
String split_punt = ""; String split_punt = "";
...@@ -772,6 +796,13 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -772,6 +796,13 @@ public class PlotConstructor2 extends ElementConstructor {
featureStr.append(key); featureStr.append(key);
} }
/**
* 除了激活下一步剧情外,还可以同时激活其他地点的剧情,可以在剧情一开始就把ABC三个地点的剧情都激活,这样就不需要先玩完A,才能玩B
* @param updateKnowledge
* @param nextPlotLocation
* @param activateExtraPlot 激活id列表
*/
public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){ public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){
JSONObject plot = null; JSONObject plot = null;
String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = ""; String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = "";
...@@ -787,7 +818,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -787,7 +818,7 @@ public class PlotConstructor2 extends ElementConstructor {
conditionName = plot.getString("conditionName"); conditionName = plot.getString("conditionName");
if(conditionName == null || conditionName.equals("")){ if(conditionName == null || conditionName.equals("")){
conditionName = "yaobuyao"; conditionName = DEFAULT_CONDITION;
} }
location = plot.getString("place"); location = plot.getString("place");
...@@ -800,7 +831,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -800,7 +831,6 @@ public class PlotConstructor2 extends ElementConstructor {
appendKnowledge(newUK, lastTaskReply, plotText); appendKnowledge(newUK, lastTaskReply, plotText);
appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId)); appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId));
appendKnowledge(newUK, plotId, "1"); appendKnowledge(newUK, plotId, "1");
//newUK.append("-<-").append(lastTaskCondition).append(":").append(conditionName).append("-<-").append(lastTaskReply).append(":").append(plotText);
} }
...@@ -818,7 +848,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -818,7 +848,7 @@ public class PlotConstructor2 extends ElementConstructor {
adjNode.put("prevAutoJump", thisAutoJump); adjNode.put("prevAutoJump", thisAutoJump);
queue.add(adjNode); queue.add(adjNode);
} else { } else {
conditionDescription.put(adjId, "剧情" + adjId + "进度"); conditionDescription.put(adjId, String.format(PLOT_STATUS, adjId));
varInitialMap.put(adjId, ""); varInitialMap.put(adjId, "");
} }
} }
...@@ -829,18 +859,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -829,18 +859,6 @@ public class PlotConstructor2 extends ElementConstructor {
*/ */
void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){ void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){
//String feature;
//如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化
//StringBuffer hisPremise = new StringBuffer();
//StringBuffer curPremise = new StringBuffer();
// appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation);
// appendPremise(hisPremise, nextLocation + "_activate_by", "match", "Include", plotId);
// appendPremise(hisPremise, nextLocation + "_activate_ready", "match", "Include", "1");
// appendPremise(hisPremise, "isNeighbour:yaobuyao", "match", "Include", "1+3+4");
JSONObject updateKnowledge = new JSONObject(); JSONObject updateKnowledge = new JSONObject();
JSONArray curPremiseList = new JSONArray(); JSONArray curPremiseList = new JSONArray();
//curPremiseList.add(curPremise.toString()); //curPremiseList.add(curPremise.toString());
...@@ -848,10 +866,14 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -848,10 +866,14 @@ public class PlotConstructor2 extends ElementConstructor {
JSONArray hisPremiseList = new JSONArray(); JSONArray hisPremiseList = new JSONArray();
//hisPremiseList.add(hisPremise.toString()); //hisPremiseList.add(hisPremise.toString());
curPremiseList.add(new Premise("yaobuyao", "match", "Include", nextLocation));
//激活下一步剧情的几个条件:1. condition 到沙滩 2. 沙滩_activate_by 沙滩的剧情是有当前剧情激活的 3. 沙滩的剧情处于等待激活的状态 4. 当前地点和沙滩地点相邻或可以直接到达
// 2.3 两个条件是特意加的
curPremiseList.add(new Premise(GOTO_CONDITION, "match", "Include", nextLocation));
hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId)); hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId));
hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1")); hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1"));
hisPremiseList.add(new Premise("isNeighbour:yaobuyao", "match", "Include", "1+3+4")); hisPremiseList.add(new Premise("isNeighbour:" + GOTO_CONDITION, "match", "Include", "1+3+4"));
......
...@@ -24,8 +24,6 @@ public class ActionMatcher { ...@@ -24,8 +24,6 @@ public class ActionMatcher {
static String API_ERROR = "api处理过程中出错了"; static String API_ERROR = "api处理过程中出错了";
public LogWriter logWriter = null; public LogWriter logWriter = null;
public UserInfo userinfo = null; public UserInfo userinfo = null;
public ServletContext context = null; public ServletContext context = null;
...@@ -35,15 +33,18 @@ public class ActionMatcher { ...@@ -35,15 +33,18 @@ public class ActionMatcher {
public WorldController worldController = null; public WorldController worldController = null;
BasicBotUtil botUtil = null; BasicBotUtil botUtil = null;
public ActionMatcher(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv, BasicBotUtil botUtil) { public ActionMatcher(Map<String ,String> curInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, BasicBotUtil botUtil) {
this.curInfoPoint = curInfoPoint; this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint; this.historyInfoPoint = botUtil.getChatCache().getInfoPoint();
this.logWriter = logWriter; this.logWriter = logWriter;
this.userinfo = userinfo; this.userinfo = userinfo;
this.context = context; this.context = context;
this.gameEnv = gameEnv;
this.worldController = new WorldController(logWriter, userinfo); this.worldController = new WorldController(logWriter, userinfo);
this.botUtil = botUtil; this.botUtil = botUtil;
if(botUtil.botType.equals("game")) {
this.gameEnv = botUtil.getChatCache().getGameEnv();
}
} }
...@@ -53,7 +54,6 @@ public class ActionMatcher { ...@@ -53,7 +54,6 @@ public class ActionMatcher {
/** /**
* 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch
* *
...@@ -235,7 +235,7 @@ public class ActionMatcher { ...@@ -235,7 +235,7 @@ public class ActionMatcher {
//没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过 //没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过
if(!activateFlag && !replaceFlag && !parentFlag) { if(!activateFlag && !replaceFlag && !parentFlag) {
logWriter.record("-----------------------------------优先级不足,跳过", 0); logWriter.record("-----------------------------------优先级不足,跳过", 0);
logWriter.record(userinfo.id2config.get(action.getId()), 1); //logWriter.record(userinfo.id2config.get(action.getId()), 1);
continue; continue;
} }
...@@ -253,33 +253,6 @@ public class ActionMatcher { ...@@ -253,33 +253,6 @@ public class ActionMatcher {
// //当前condition的辅助优先级高于bestMatch、或者优先级已知添加数量更多、或者
// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.activePriority > bestMatch.activePriority)
// || action.featureMap.get("activate") != null
// || bestMatch.nextStep.contains(String.valueOf(action.id)) || (!action.configName.equals("") && bestMatch.nextStep.contains(action.configName.substring(0,3)))){
// //激活优先级先比较,但是如果激活的是无条件的就直接判断名字。
// if(conditionSatisfy(action)){
//
// //有激活配置文件,但是没有post提交表单,则激活,如果有post就放到提交表单之后激活(postActivate)
// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) {
// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context);
// }
//
// bestMatch = action;
// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2);
// logWriter.writeln();
//
// }
//
// } else {
// logWriter.record("-----------------------------------优先级不足,跳过", 0);
// logWriter.record(userinfo.id2config.get(action.id), 1);
// }
} }
return bestMatch; return bestMatch;
...@@ -887,7 +860,8 @@ public class ActionMatcher { ...@@ -887,7 +860,8 @@ public class ActionMatcher {
}else if(postType.equals("term")){ }else if(postType.equals("term")){
poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansAction, url); poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansAction, url);
}else if(postType.equals("gameQA")){ }else if(postType.equals("gameQA")){
poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo); System.out.println("提交表单" + gameEnv);
poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo);
} }
return ans; return ans;
......
...@@ -30,7 +30,7 @@ public class ChatCacheController { ...@@ -30,7 +30,7 @@ public class ChatCacheController {
private static String ENV_POSTFIX = "-env.data"; private static String ENV_POSTFIX = "-env.data";
private static String INFO_POSTFIX = "-info.data"; private static String INFO_POSTFIX = "-info.data";
public static String COMBINE_PUNC1 = "@@@"; public static String COMBINE_PUNC1 = "@@@"; //chatKey的连接符 chatKey格式为 用户名@@@bot账号@@@@随机码
public static String COMBINE_PUNC2 = "@@@@"; public static String COMBINE_PUNC2 = "@@@@";
...@@ -41,7 +41,7 @@ public class ChatCacheController { ...@@ -41,7 +41,7 @@ public class ChatCacheController {
* *
* @return 历史信息点,对话过程中引擎提取的用户信息 * @return 历史信息点,对话过程中引擎提取的用户信息
*/ */
public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map<String, String[]> receiveParamters, Boolean loadCacheStatus) throws Exception { public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, String botType) throws Exception {
Map<String, ChatCache> chatCacheMap = null; Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null; ChatCache chatCache = null;
...@@ -60,7 +60,7 @@ public class ChatCacheController { ...@@ -60,7 +60,7 @@ public class ChatCacheController {
//如果用户之前没有玩过或者有一段时间没有玩 //如果用户之前没有玩过或者有一段时间没有玩
if(chatCache == null){ if(chatCache == null){
chatCache = new ChatCache(userinfo, userKey, randKey); chatCache = new ChatCache(userinfo, userKey, randKey, botType);
chatCacheMap.put(userKey, chatCache); chatCacheMap.put(userKey, chatCache);
//用户几分钟前还在玩 //用户几分钟前还在玩
} else { } else {
...@@ -69,7 +69,7 @@ public class ChatCacheController { ...@@ -69,7 +69,7 @@ public class ChatCacheController {
if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) {
ChatCacheController.saveChatCache(chatCache, null); ChatCacheController.saveChatCache(chatCache, null);
} }
chatCache = new ChatCache(userinfo, userKey, randKey); chatCache = new ChatCache(userinfo, userKey, randKey, botType);
chatCacheMap.put(userKey, chatCache); chatCacheMap.put(userKey, chatCache);
} }
} }
...@@ -79,9 +79,10 @@ public class ChatCacheController { ...@@ -79,9 +79,10 @@ public class ChatCacheController {
e.printStackTrace(); e.printStackTrace();
//chatCache = new ChatCache(userinfo, userKey, randKey); //chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache); //chatCacheMap.put(userKey, chatCache);
} }
System.out.println(chatCache.getGameEnv());
return chatCache; return chatCache;
} }
...@@ -235,12 +236,13 @@ public class ChatCacheController { ...@@ -235,12 +236,13 @@ public class ChatCacheController {
/** /**
* 根据chatKey更新chatCache的数据,并修改最后更新时间 * 根据chatKey更新chatCache的数据,并修改最后更新时间
*/ */
public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, ChatCache chatCache, ServletContext context, UserInfo userInfo) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); chatCache.getInfoPoint().put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache"); Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); keyCacheMap.put(chatCache.getUserKey(), chatCache);
chatCache.setInfoPoint(historyInfoPoint); //ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey"));
chatCache.setGameEnv(gameEnv); //chatCache.setInfoPoint(historyInfoPoint);
//chatCache.setGameEnv(gameEnv);
context.setAttribute("chatCache", keyCacheMap); context.setAttribute("chatCache", keyCacheMap);
} }
......
package com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.UserInfo;
import javax.servlet.ServletContext;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ConditionTableController {
public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException {
int id = Integer.parseInt(configId);
Condition condition = new Condition();
UserInfoController userInfoController = new UserInfoController();
//data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(",");
String conditionName = "";
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userInfo = (UserInfo) context.getAttribute(userName);
if (userInfo.id2config.containsKey(id)) {
Condition oldCondition = userInfo.id2condition.get(id);
//-------------------
try {
conditionName = oldCondition.indexName;
} catch (Exception e) {
e.printStackTrace();
}
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == id) {
condIter.remove();
}
}
}
userInfo.name2condition.remove(oldCondition.configName);
userInfo.id2config.remove(id);
userInfo.id2condition.remove(id);
} else {
System.out.println("未找到要删除的configId");
}
return true;
}
public static boolean batchDeleteConfig(String userName, List<Integer> idGroup, UserInfo userInfo) throws IOException {
Condition condition = new Condition();
String conditionName = "";
for (int configId : idGroup) {
if (userInfo.id2config.containsKey(configId)) {
Condition oldCondition = userInfo.id2condition.get(configId);
try {
conditionName = oldCondition.indexName;
} catch (Exception e) {
e.printStackTrace();
}
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) {
Condition c = condIter.next();
if (c.id == configId) {
condIter.remove();
}
}
}
userInfo.name2condition.remove(oldCondition.configName);
userInfo.id2config.remove(configId);
userInfo.id2condition.remove(configId);
} else {
System.out.println("未找到要删除的configId:" + configId);
}
}
return true;
}
public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
String conditionNameList[];
UserInfoController userInfoController = new UserInfoController();
int id = Integer.parseInt(configId);
condition = userInfoController.buildCondition(condition, configLine);
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.conditionTable.get(condition.indexName) == null) {
List<Condition> conditionList = new ArrayList<Condition>();
userinfo.conditionTable.put(condition.indexName, conditionList);
}
if(!condition.configName.equals("")){
userinfo.name2condition.put(condition.configName, condition);
}
userinfo.conditionTable.get(condition.indexName).add(condition);
userinfo.id2config.put(id, configLine);
userinfo.id2condition.put(id, condition);
return true;
}
public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---", -1);
String name = dataPair[0], value = dataPair[1];
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.put(name, value);
return true;
}
public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException {
//data=configLine+"---"+conditionNameList
String name = data;
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
userinfo.varInitialMap.remove(name);
return true;
}
public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException {
UserInfoController userInfoController = new UserInfoController();
if (context.getAttribute(userName) == null) {
userInfoController.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String extraElements[] = data.split("\\|");
userinfo.extraInfo.put(extraElements[1], extraElements[2]);
return true;
}
public static String writeConfigText(String userName, UserInfo userinfo) throws IOException {
String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText;
String path = CONFIG_DIR + "/" + userName + ".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir") + "/config");
System.out.println(userName);
System.out.println("config_dir" + dir.getAbsolutePath());
String returnMessage = "success";
if (!dir.exists())
dir.mkdir();
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
try {
Iterator<String> keyIter = userinfo.extraInfo.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
if (!userinfo.extraInfo.get(info).equals(""))
bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n");
}
keyIter = userinfo.varInitialMap.keySet().iterator();
while (keyIter.hasNext()) {
String info = keyIter.next();
bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n");
}
Iterator<Integer> idIter = userinfo.id2config.keySet().iterator();
while (idIter.hasNext()) {
int id = idIter.next();
bw.write(userinfo.id2config.get(id) + "\n");
}
bw.write("\n");
} catch (Exception e) {
e.printStackTrace();
returnMessage = "config file write error";
} finally {
bw.close();
fw.close();
}
return returnMessage;
}
}
...@@ -253,6 +253,9 @@ public class FormsPoster { ...@@ -253,6 +253,9 @@ public class FormsPoster {
if(historyInfoPoint.get("common_answer") != null && (historyInfoPoint.get("common_answer").equals("") || historyInfoPoint.get("common_answer").equals("no answer"))){ if(historyInfoPoint.get("common_answer") != null && (historyInfoPoint.get("common_answer").equals("") || historyInfoPoint.get("common_answer").equals("no answer"))){
postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo); postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo);
} }
// historyInfoPoint.put("common_answer", "【旁白@%正常】QA暂时关闭");
// historyInfoPoint.put("qa_score", "99");
// historyInfoPoint.put("qa_status", "OK");
} }
......
...@@ -134,12 +134,12 @@ public class SimpleUtil { ...@@ -134,12 +134,12 @@ public class SimpleUtil {
try { try {
HttpResponse resp = client.execute(httpPost); HttpResponse resp = client.execute(httpPost);
jobj.put("status_code", resp.getStatusLine().getStatusCode());
if (resp.getStatusLine().getStatusCode() == 200) { if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity(); HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8"); respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent); jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1); jobj.put("post_status", 1);
} else { } else {
jobj.put("post_status", 0); jobj.put("post_status", 0);
jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase()); jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase());
......
...@@ -8,12 +8,15 @@ import java.io.*; ...@@ -8,12 +8,15 @@ import java.io.*;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR;
public class UserInfoController { public class UserInfoController {
static String CONFIG_DIR = System.getProperty("user.dir") + "/config"; static String CONFIG_DIR = System.getProperty("user.dir") + "/config";
static String FILE_ERROR = ".txt文件有误"; static String FILE_ERROR = ".txt文件有误";
/** /**
* 根据本地配置文件生成用户信息 * 根据本地配置文件生成用户信息
*/ */
...@@ -82,6 +85,12 @@ public class UserInfoController { ...@@ -82,6 +85,12 @@ public class UserInfoController {
} }
/**
* 解析一行配置文件
* @param action
* @param line
* @return
*/
public static Action buildCondition(Action action, String line) { public static Action buildCondition(Action action, String line) {
String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[]; String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[];
...@@ -90,8 +99,6 @@ public class UserInfoController { ...@@ -90,8 +99,6 @@ public class UserInfoController {
text = line.split("---"); text = line.split("---");
if (line.startsWith("yaobuyao::match-Keyword=+海边|game_step::match-Include=9826795627_plot_1-2,1-2::number-BiggerOrEqual=1|match,updateKnowledge-<-unknownText:-<-site:武器库-<--<-game_step:9826795627_plot_1-5-<-unknownText:还没到下一个地点-<-site:武器库-<-npc_update:updateFollowerLocation:武"))
System.out.println("xxx");
line = text[0]; line = text[0];
if(text.length > 1 && text[1].startsWith("<-")) if(text.length > 1 && text[1].startsWith("<-"))
line += "---" + text[1]; line += "---" + text[1];
...@@ -102,10 +109,14 @@ public class UserInfoController { ...@@ -102,10 +109,14 @@ public class UserInfoController {
cur_premises = premises[0].split(","); cur_premises = premises[0].split(",");
history_premises = premises[1].split(","); history_premises = premises[1].split(",");
if (premises.length < 4)
action.setAuxiliaryPriority(0); action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1]));
else //action.setConfigName(premises[4].split("=", 2)[1]);
action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1]));
next = element[1].split("\\|");
if (next.length < 4)
return action;
if(premises.length < 5) if(premises.length < 5)
action.setConfigName(""); action.setConfigName("");
...@@ -113,11 +124,9 @@ public class UserInfoController { ...@@ -113,11 +124,9 @@ public class UserInfoController {
action.setConfigName(premises[4].split("=", 2)[1]); action.setConfigName(premises[4].split("=", 2)[1]);
next = element[1].split("\\|");
if (next.length < 4) //回答可以有多个,然后可随机选择一个
return action;
action.setAnswer(next[0].split("~")); action.setAnswer(next[0].split("~"));
//action.nextStep = next[1];
//第二处 //第二处
action.setNextStep(next[1].split("=", 2)[1]); action.setNextStep(next[1].split("=", 2)[1]);
action.setId(Integer.parseInt(next[3].split("=")[1])); action.setId(Integer.parseInt(next[3].split("=")[1]));
...@@ -171,7 +180,7 @@ public class UserInfoController { ...@@ -171,7 +180,7 @@ public class UserInfoController {
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
e.printStackTrace(); e.printStackTrace();
System.out.println(line); System.out.println(line);
System.out.println("文本格式有误"); System.out.println(TEXT_PARSE_ERROR);
} }
return action; return action;
} }
...@@ -235,7 +244,7 @@ public class UserInfoController { ...@@ -235,7 +244,7 @@ public class UserInfoController {
} }
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数据格式有误"); System.out.println(TEXT_PARSE_ERROR);
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) { } catch (Exception e) {
......
...@@ -3,7 +3,6 @@ package com.qiwu.chatbotbackend.processing; ...@@ -3,7 +3,6 @@ package com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2;
import com.qiwu.chatbotbackend.task.utils.GameBotUtil; import com.qiwu.chatbotbackend.task.utils.GameBotUtil;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -11,6 +10,8 @@ import java.util.List; ...@@ -11,6 +10,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import static com.qiwu.chatbotbackend.Config.Config.*;
public class WorldController { public class WorldController {
public LogWriter logWriter = null; public LogWriter logWriter = null;
public UserInfo userInfo = null; public UserInfo userInfo = null;
...@@ -41,7 +42,7 @@ public class WorldController { ...@@ -41,7 +42,7 @@ public class WorldController {
subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2);
returnStr = gameEnv.queryGoodsIntroByGoodsName(subValuePair[1]); returnStr = gameEnv.queryGoodsIntroByGoodsName(subValuePair[1]);
if(returnStr == null ) if(returnStr == null )
returnStr = "无"; returnStr = DONT_FOUND;
break; break;
case "queryAttrByGoodsName": case "queryAttrByGoodsName":
...@@ -49,16 +50,16 @@ public class WorldController { ...@@ -49,16 +50,16 @@ public class WorldController {
value = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]); value = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]);
if(returnStr == null) { if(returnStr == null) {
returnStr = "没找到"; returnStr = DONT_FOUND;
}else{ }else{
returnStr = userInfo.varInitialMap.get("GET_ITEM_ATTR").replace("[物品名]", subValuePair[0]).replace("[属性名]", subValuePair[1]).replace("[属性值]", value); returnStr = userInfo.varInitialMap.get("GET_ITEM_ATTR").replace(ITEM_NAME_SLOT, subValuePair[0]).replace(ATTR_NAME_SLOT, subValuePair[1]).replace(ATTR_VALUE_SLOT, value);
} }
break; break;
case "queryAllAttrByGoodsName": case "queryAllAttrByGoodsName":
textList = gameEnv.queryGoodsAllAttrByGoodsName(varName); textList = gameEnv.queryGoodsAllAttrByGoodsName(varName);
if(textList == null || textList.size() == 0) if(textList == null || textList.size() == 0)
returnStr = "无"; returnStr = DONT_FOUND;
else { else {
for (String site : textList) for (String site : textList)
returnStr += "、" + site; returnStr += "、" + site;
...@@ -68,7 +69,7 @@ public class WorldController { ...@@ -68,7 +69,7 @@ public class WorldController {
case "queryAroundGoodsByClassName": case "queryAroundGoodsByClassName":
textList = gameEnv.queryGoodsByClassAndSite(namePair[1], historyInfoPoint.get("site")); textList = gameEnv.queryGoodsByClassAndSite(namePair[1], historyInfoPoint.get("site"));
if(textList == null || textList.size() == 0) if(textList == null || textList.size() == 0)
returnStr = "无"; returnStr = DONT_FOUND;
else { else {
for (String site : textList) for (String site : textList)
returnStr += "、" + site; returnStr += "、" + site;
...@@ -82,14 +83,14 @@ public class WorldController { ...@@ -82,14 +83,14 @@ public class WorldController {
ItemName = gameEnv.getGoodsNameByNickname(currentLocation, ItemName); ItemName = gameEnv.getGoodsNameByNickname(currentLocation, ItemName);
returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问");
if(returnStr == null || returnStr.equals("否")){ if(returnStr == null || returnStr.equals("否")){
returnStr = "隐藏了"; returnStr = ATTRIBUTE_HIDDEN;
} else if(returnStr.equals("是")){ } else if(returnStr.equals("是")){
location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location");
if(location == null){ if(location == null){
returnStr = "没找到"; returnStr = DONT_FOUND;
}else{ }else{
owner = gameEnv.queryGoodsAttrByGoodsName(ItemName, "所属角色"); owner = gameEnv.queryGoodsAttrByGoodsName(ItemName, "owner");
logWriter.record(ItemName + "-owner:" + owner, 0); //logWriter.record(ItemName + "-owner:" + owner, 0);
if(owner != null && !owner.equals("")){ if(owner != null && !owner.equals("")){
//如果物品的所属角色是玩家,那么回答物品在你身上 //如果物品的所属角色是玩家,那么回答物品在你身上
...@@ -97,11 +98,14 @@ public class WorldController { ...@@ -97,11 +98,14 @@ public class WorldController {
returnStr = userInfo.varInitialMap.get("ITEM_IS_YOURS"); returnStr = userInfo.varInitialMap.get("ITEM_IS_YOURS");
}else { }else {
//不然回答物品在某个人身上 //不然回答物品在某个人身上
returnStr = userInfo.varInitialMap.get("FIND_TEM_OWNER").replace("[物品名]", ItemName).replace("[人名]", owner); if(userInfo.varInitialMap.get("FIND_ITEM_OWNER") == null)
userInfo.varInitialMap.put("FIND_ITEM_OWNER", FIND_ITEM_OWNER);
System.out.println("pattern:" + userInfo.varInitialMap.get("FIND_ITEM_OWNER") + ", ItemName:" + ItemName + ", owner:" + owner);
returnStr = userInfo.varInitialMap.get("FIND_ITEM_OWNER").replace(ITEM_NAME_SLOT, ItemName).replace(NPC_NAME_SLOT, owner);
} }
}else { }else {
//没有所属角色就回答物品在某个地点 //没有所属角色就回答物品在某个地点
returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace("[物品名]", ItemName).replace("[地点]", location); returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace(ITEM_NAME_SLOT, ItemName).replace(SITE_SLOT, location);
} }
} }
} }
...@@ -110,12 +114,12 @@ public class WorldController { ...@@ -110,12 +114,12 @@ public class WorldController {
String player = gameEnv.queryPlayerName(); String player = gameEnv.queryPlayerName();
textList = gameEnv.queryGoodsByNpcName(player); textList = gameEnv.queryGoodsByNpcName(player);
if(textList == null || textList.size() == 0) if(textList == null || textList.size() == 0)
returnStr = "什么都没有"; returnStr = NOTHING_FOUND;
else { else {
for (String site : textList) for (String site : textList)
returnStr += "、" + site; returnStr += "、" + site;
returnStr = userInfo.varInitialMap.get("WE_HAVE").replace("[物品列表]", returnStr.substring(1)); returnStr = userInfo.varInitialMap.get("WE_HAVE").replace(ITEM_LIST_SLOT, returnStr.substring(1));
} }
break; break;
...@@ -126,13 +130,13 @@ public class WorldController { ...@@ -126,13 +130,13 @@ public class WorldController {
ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1];
returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问");
if(returnStr == null || returnStr.equals("否")){ if(returnStr == null || returnStr.equals("否")){
returnStr = "没找到"; returnStr = DONT_FOUND;
} else if(returnStr.equals("是")){ } else if(returnStr.equals("是")){
location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location");
if(location == null){ if(location == null){
returnStr = "没找到"; returnStr = DONT_FOUND;
}else{ }else{
returnStr = userInfo.varInitialMap.get("FIND_ITEM_WAY").replace("[物品名]", ItemName).replace("[地点]", location); returnStr = userInfo.varInitialMap.get("FIND_ITEM_WAY").replace(ITEM_NAME_SLOT, ItemName).replace(SITE_SLOT, location);
} }
} }
...@@ -147,7 +151,7 @@ public class WorldController { ...@@ -147,7 +151,7 @@ public class WorldController {
subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2);
returnStr = gameEnv.queryNpcIntroByNpcName(subValuePair[1]); returnStr = gameEnv.queryNpcIntroByNpcName(subValuePair[1]);
if(returnStr == null) if(returnStr == null)
returnStr = "无"; returnStr = DONT_FOUND;
break; break;
case "queryAttrByNPCName": case "queryAttrByNPCName":
...@@ -156,10 +160,10 @@ public class WorldController { ...@@ -156,10 +160,10 @@ public class WorldController {
subValuePair[0] = subValuePair[0].replace("哪里", "location"); subValuePair[0] = subValuePair[0].replace("哪里", "location");
value = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); value = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]);
if(value == null) { if(value == null) {
returnStr = "没找到"; returnStr = DONT_FOUND;
}else{ }else{
returnStr = userInfo.varInitialMap.get("GET_NPC_ATTR").replace("[人名]", subValuePair[0]).replace("[属性名]", subValuePair[1]).replace("[属性值]", value); returnStr = userInfo.varInitialMap.get("GET_NPC_ATTR").replace(NPC_NAME_SLOT, subValuePair[0]).replace(ATTR_NAME_SLOT, subValuePair[1]).replace(ATTR_VALUE_SLOT, value);
} }
break; break;
...@@ -169,7 +173,7 @@ public class WorldController { ...@@ -169,7 +173,7 @@ public class WorldController {
location = gameEnv.queryNpcAttrByNpcName(valuePair[1], "location"); location = gameEnv.queryNpcAttrByNpcName(valuePair[1], "location");
if(location == null){ if(location == null){
returnStr = "没找到"; returnStr = DONT_FOUND;
}else{ }else{
returnStr = location; returnStr = location;
} }
...@@ -183,15 +187,15 @@ public class WorldController { ...@@ -183,15 +187,15 @@ public class WorldController {
System.out.println(NPCName); System.out.println(NPCName);
returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问");
if(returnStr == null || returnStr.equals("否")){ if(returnStr == null || returnStr.equals("否")){
returnStr = "没找到"; returnStr = DONT_FOUND;
} else if(returnStr.equals("是")){ } else if(returnStr.equals("是")){
location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); location = gameEnv.queryNpcAttrByNpcName(NPCName, "location");
if(location == null){ if(location == null){
returnStr = "没找到"; returnStr = DONT_FOUND;
}else{ }else{
returnStr = userInfo.varInitialMap.get("FIND_NPC_LOCATION").replace("[人名]", NPCName).replace("[地点]", location); returnStr = userInfo.varInitialMap.get("FIND_NPC_LOCATION").replace(NPC_NAME_SLOT, NPCName).replace(SITE_SLOT2, location);
} }
} }
break; break;
...@@ -202,13 +206,13 @@ public class WorldController { ...@@ -202,13 +206,13 @@ public class WorldController {
NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1];
returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问");
if(returnStr == null || returnStr.equals("否")){ if(returnStr == null || returnStr.equals("否")){
returnStr = "没找到"; returnStr = DONT_FOUND;
} else if(returnStr.equals("是")){ } else if(returnStr.equals("是")){
location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); location = gameEnv.queryNpcAttrByNpcName(NPCName, "location");
if(location == null){ if(location == null){
returnStr = "没找到"; returnStr = DONT_FOUND;
}else{ }else{
returnStr = userInfo.varInitialMap.get("FIND_NPC_WAY").replace("[人名]", NPCName).replace("[地点]", location); returnStr = userInfo.varInitialMap.get("FIND_NPC_WAY").replace(NPC_NAME_SLOT, NPCName).replace(SITE_SLOT2, location);
} }
} }
...@@ -221,7 +225,7 @@ public class WorldController { ...@@ -221,7 +225,7 @@ public class WorldController {
lastTalker = m.group(1); lastTalker = m.group(1);
} }
returnStr = userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); returnStr = userInfo.varInitialMap.get("WHO_YOU_ARE").replace(NPC_NAME_SLOT, lastTalker);
break; break;
...@@ -236,16 +240,13 @@ public class WorldController { ...@@ -236,16 +240,13 @@ public class WorldController {
switch (valuePair[0]) { switch (valuePair[0]) {
case "queryAroundAllBySite": case "queryAroundAllBySite":
if(userInfo.varInitialMap.containsKey("AROUND_THINGS")) { format = userInfo.varInitialMap.get("AROUND_THINGS");
format = userInfo.varInitialMap.get("AROUND_THINGS");
}else {
format = "周围有[人物物品列表]";
}
sites = gameEnv.queryAroundAllBySite(historyInfoPoint.get("site")); sites = gameEnv.queryAroundAllBySite(historyInfoPoint.get("site"));
if(sites == null || sites.size() == 0) if(sites == null || sites.size() == 0)
returnStr = "什么都没有"; returnStr = NOTHING_FOUND;
else { else {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
...@@ -254,20 +255,16 @@ public class WorldController { ...@@ -254,20 +255,16 @@ public class WorldController {
text.append("、" + site); text.append("、" + site);
} }
returnStr = format.replace("[人物物品列表]", text.substring(1)); returnStr = format.replace(NPC_ITEM_LIST_SLOT, text.substring(1));
} }
break; break;
case "queryAroundNpcBySite": case "queryAroundNpcBySite":
if(userInfo.varInitialMap.containsKey("AROUND_PEOPLE")) { format = userInfo.varInitialMap.get("AROUND_PEOPLE");
format = userInfo.varInitialMap.get("AROUND_PEOPLE");
}else {
format = "周围有[人物列表]";
}
sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site"));
if(sites == null || sites.size() == 0) if(sites == null || sites.size() == 0)
returnStr = "什么都没有"; returnStr = NOTHING_FOUND;
else { else {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
...@@ -276,20 +273,16 @@ public class WorldController { ...@@ -276,20 +273,16 @@ public class WorldController {
text.append("、" + site); text.append("、" + site);
} }
returnStr = format.replace("[人物列表]", text.substring(1)); returnStr = format.replace(NPC_LIST_SLOT, text.substring(1));
} }
break; break;
case "queryAroundGoodsBySite": case "queryAroundGoodsBySite":
if(userInfo.varInitialMap.containsKey("AROUND_ITEMS")) { format = userInfo.varInitialMap.get("AROUND_ITEMS");
format = userInfo.varInitialMap.get("AROUND_ITEMS");
}else {
format = "周围有[物品列表]";
}
sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site")); sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site"));
if(sites == null || sites.size() == 0) if(sites == null || sites.size() == 0)
returnStr = "什么都没有"; returnStr = NOTHING_FOUND;
else { else {
if(sites.size() > 0) { if(sites.size() > 0) {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
...@@ -297,17 +290,13 @@ public class WorldController { ...@@ -297,17 +290,13 @@ public class WorldController {
for(String site:sites){ for(String site:sites){
text.append("、" + site); text.append("、" + site);
} }
returnStr = format.replace("[物品列表]", text.substring(1)); returnStr = format.replace(ITEM_LIST_SLOT, text.substring(1));
} }
} }
break; break;
case "queryCanGoBySite": case "queryCanGoBySite":
if(userInfo.varInitialMap.containsKey("CAN_GO_SITES")) { format = userInfo.varInitialMap.get("CAN_GO_SITES");
format = userInfo.varInitialMap.get("CAN_GO_SITES");
}else {
format = "你可以去[可去列表]";
}
sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site"));
if(sites == null) { if(sites == null) {
...@@ -322,17 +311,13 @@ public class WorldController { ...@@ -322,17 +311,13 @@ public class WorldController {
for(String site:sites){ for(String site:sites){
text.append("、" + site); text.append("、" + site);
} }
returnStr = format.replace("[可去列表]", text.substring(1)); returnStr = format.replace(CAN_GO_SITE_SLOT, text.substring(1));
} }
} }
break; break;
case "queryHowToPathBySite": case "queryHowToPathBySite":
if(userInfo.varInitialMap.containsKey("PATH_EXIST")) { format = userInfo.varInitialMap.get("PATH_EXIST");
format = userInfo.varInitialMap.get("PATH_EXIST");
}else {
format = "通过[途径]可以到达[目的地]";
}
if(!currentInfoPoint.containsKey(valuePair[1])) { if(!currentInfoPoint.containsKey(valuePair[1])) {
returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST"); returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST");
...@@ -352,17 +337,14 @@ public class WorldController { ...@@ -352,17 +337,14 @@ public class WorldController {
for(String site:sites){ for(String site:sites){
text.append("、" + site); text.append("、" + site);
} }
returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", destination); returnStr = format.replace(PATH_SLOT, text.substring(1)).replace(DESTINATION_SLOT, destination);
} }
} }
break; break;
case "queryToDoPathBySite": case "queryToDoPathBySite":
if(userInfo.varInitialMap.containsKey("SITE_NOT_ADJOINT")) { format = userInfo.varInitialMap.get("SITE_NOT_ADJOINT");
format = userInfo.varInitialMap.get("SITE_NOT_ADJOINT");
}else {
format = "通过[途径]可以到达[目的地]";
}
destination = currentInfoPoint.get(valuePair[1]).split(":")[1]; destination = currentInfoPoint.get(valuePair[1]).split(":")[1];
destination = gameEnv.getPlaceNameByNickname(start, destination); destination = gameEnv.getPlaceNameByNickname(start, destination);
...@@ -381,7 +363,7 @@ public class WorldController { ...@@ -381,7 +363,7 @@ public class WorldController {
for(String site:sites){ for(String site:sites){
text.append("、" + site); text.append("、" + site);
} }
returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", destination); returnStr = format.replace(PATH_SLOT, text.substring(1)).replace(DESTINATION_SLOT, destination);
} }
} }
break; break;
...@@ -390,16 +372,13 @@ public class WorldController { ...@@ -390,16 +372,13 @@ public class WorldController {
returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination;
break; break;
case "queryAroundPlace": case "queryAroundPlace":
if(userInfo.varInitialMap.containsKey("AROUND_PLACE")) {
format = userInfo.varInitialMap.get("AROUND_PLACE"); format = userInfo.varInitialMap.get("AROUND_PLACE");
}else {
format = "周围有[地点列表]";
}
sites = gameEnv.queryCanGoBySite(start); sites = gameEnv.queryCanGoBySite(start);
if(sites == null || sites.size() == 0) { if(sites == null || sites.size() == 0) {
returnStr = "无处可去了"; returnStr = NOWHERE_CAN_GO;
} else { } else {
if(sites.size() > 0) { if(sites.size() > 0) {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
...@@ -407,21 +386,17 @@ public class WorldController { ...@@ -407,21 +386,17 @@ public class WorldController {
for(String site:sites){ for(String site:sites){
text.append("、" + site); text.append("、" + site);
} }
returnStr = format.replace("[地点列表]", text.substring(1)); returnStr = format.replace(SITE_LIST_SLOT, text.substring(1));
} }
} }
break; break;
case "queryInnerNpcBySite": case "queryInnerNpcBySite":
if(userInfo.varInitialMap.containsKey("INNER_PEOPLE")) { format = userInfo.varInitialMap.get("INNER_PEOPLE");
format = userInfo.varInitialMap.get("INNER_PEOPLE");
}else {
format = "里面有[人物列表]";
}
sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site"));
if(sites == null || sites.size() == 0) if(sites == null || sites.size() == 0)
returnStr = "什么都没有"; returnStr = NOTHING_FOUND;
else { else {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
...@@ -430,30 +405,33 @@ public class WorldController { ...@@ -430,30 +405,33 @@ public class WorldController {
text.append("、" + site); text.append("、" + site);
} }
returnStr = format.replace("[人物列表]", text.substring(1)); returnStr = format.replace(NPC_LIST_SLOT, text.substring(1));
} }
break; break;
case "queryTaskDescription": case "queryTaskDescription":
if(userInfo.varInitialMap.containsKey("TASK_DESCRIPTION")) { format = userInfo.varInitialMap.get("TASK_DESCRIPTION");
format = userInfo.varInitialMap.get("TASK_DESCRIPTION");
}else {
format = "我们的任务是[任务描述]";
}
returnStr = format.replace("[任务描述]", userInfo.varInitialMap.get(PlotConstructor2.TASK_DESCRIPTION)); returnStr = format.replace(TASK_DESCRIPTION_SLOT, userInfo.varInitialMap.get(TASK_DESCRIPTION));
break; break;
case "queryWhereIam": case "queryWhereIam":
returnStr = userInfo.varInitialMap.get("WHERE_I_AM").replace("[地点名]", historyInfoPoint.get("site")); returnStr = userInfo.varInitialMap.get("WHERE_I_AM").replace(SITE_SLOT, historyInfoPoint.get("site"));
break; break;
case "queryPathAt": case "queryPathAt":
returnStr = userInfo.varInitialMap.get("PATH_AT").replace("[地点名]", historyInfoPoint.get("site")); returnStr = userInfo.varInitialMap.get("PATH_AT").replace(SITE_SLOT, historyInfoPoint.get("site"));
break; break;
case "queryPathAdjoin": case "queryPathAdjoin":
returnStr = userInfo.varInitialMap.get("PATH_ADJOINT"); returnStr = userInfo.varInitialMap.get("PATH_ADJOINT");
break; break;
case "queryItemsInPlace":
break;
case "queryNPCInPlace":
break;
case "queryThingsInPlace":
break;
} }
} }
......
...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet; ...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.*; import com.qiwu.chatbotbackend.gameDesign.*;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController;
...@@ -21,6 +21,8 @@ import java.time.LocalDateTime; ...@@ -21,6 +21,8 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.Config.Config.CONDITION_GENERATE_URL;
@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"})
public class GameDesignServlet extends HttpServlet { public class GameDesignServlet extends HttpServlet {
...@@ -166,8 +168,8 @@ public class GameDesignServlet extends HttpServlet { ...@@ -166,8 +168,8 @@ public class GameDesignServlet extends HttpServlet {
helper.batchInsertVariableByBotId(botId, constructor); helper.batchInsertVariableByBotId(botId, constructor);
List<JSONObject> jsonList = new ArrayList<JSONObject>(); List<JSONObject> jsonList = new ArrayList<JSONObject>();
for(ConfigTerm configTerm : constructor.getConfigTermList()){ for(ConfigTermText configTermText : constructor.getConfigTermTextList()){
json = configTerm.toJson(constructor.getConditionDescription()); json = configTermText.toJson(constructor.getConditionDescription());
constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName);
jsonList.add(json); jsonList.add(json);
} }
...@@ -296,7 +298,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -296,7 +298,7 @@ public class GameDesignServlet extends HttpServlet {
userInfo.extraInfo.put("activeAction", startCondition); userInfo.extraInfo.put("activeAction", startCondition);
try { try {
returnMessage = SimpleUtil.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth")); returnMessage = SimpleUtil.postJSON(CONDITION_GENERATE_URL, actionPostData, (String)gameElements.get("auth"));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -316,7 +318,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -316,7 +318,7 @@ public class GameDesignServlet extends HttpServlet {
public void readKeywords(Map<String, StringBuffer> keywordsMap, String path){ public void readKeywords(Map<String, StringBuffer> keywordsMap, String path){
File file = new File(path); File file = new File(path);
String line, pair[]; String line, elem[];
if(file.exists()){ if(file.exists()){
FileReader reader = null; FileReader reader = null;
...@@ -326,10 +328,23 @@ public class GameDesignServlet extends HttpServlet { ...@@ -326,10 +328,23 @@ public class GameDesignServlet extends HttpServlet {
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
if(!line.equals("") && !line.startsWith("#")){ if(!line.equals("") && !line.startsWith("#")) {
pair = line.split("\\|", 2); elem = line.split("\\|", 3);
keywordsMap.put(pair[0], new StringBuffer(pair[1]));
//查看意图是否已经存在相关的condition,如果已经存在就append,如果不存在就初始化
if (!elem[1].equals("pattern")) {
if (keywordsMap.get(elem[0]) == null) {
keywordsMap.put(elem[0], new StringBuffer(elem[1]));
} else {
keywordsMap.get(elem[0]).append(",").append(elem[1]);
}
}
//根据意图和condition名字添加关键字
keywordsMap.put(elem[0] + "_" + elem[1], new StringBuffer(elem[2]));
} }
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
......
...@@ -21,6 +21,9 @@ import java.text.ParseException; ...@@ -21,6 +21,9 @@ import java.text.ParseException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC2;
import static com.qiwu.chatbotbackend.Config.Config.TEST_VAR;
@WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"}) @WebServlet(name = "GetAnswerServlet", urlPatterns = {"/test", "/test/", "/dialog"})
public class GetAnswerServlet extends HttpServlet { public class GetAnswerServlet extends HttpServlet {
...@@ -36,7 +39,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -36,7 +39,7 @@ public class GetAnswerServlet extends HttpServlet {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
Map<String, String[]> receiveParamters = new HashMap<>(request.getParameterMap()); Map<String, String[]> receiveParamters = new HashMap<>(request.getParameterMap());
Map<String ,String> curInfoPoint = new HashMap<String, String>(); Map<String ,String> curInfoPoint = new HashMap<String, String>();
Map<String, String> historyInfoPoint = null; //Map<String, String> historyInfoPoint = null;
Solution bestMatch = null; Solution bestMatch = null;
BasicBotUtil botUtil = null; BasicBotUtil botUtil = null;
Action ansAction = null; Action ansAction = null;
...@@ -49,7 +52,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -49,7 +52,7 @@ public class GetAnswerServlet extends HttpServlet {
//如果有client_id,会用@分隔 //如果有client_id,会用@分隔
chatKey = receiveParamters.get("chat_key")[0]; chatKey = receiveParamters.get("chat_key")[0];
String chatKeys[] = receiveParamters.get("chat_key")[0].split("@@@@"); String chatKeys[] = receiveParamters.get("chat_key")[0].split(COMBINE_PUNC2);
if(chatKeys.length == 1){ if(chatKeys.length == 1){
userKey = chatKeys[0]; userKey = chatKeys[0];
randKey = chatKeys[0]; randKey = chatKeys[0];
...@@ -83,12 +86,20 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -83,12 +86,20 @@ public class GetAnswerServlet extends HttpServlet {
//获得用户历史信息 //获得用户历史信息
ChatCache chatCache = null; ChatCache chatCache = null;
Boolean loadCacheStatus = Boolean.valueOf(false); Boolean loadCacheStatus = Boolean.valueOf(false);
if(userinfo.varInitialMap.get("botType") != null)
botType = userinfo.varInitialMap.get("botType");
try { try {
chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus); chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType);
} catch (SQLException e) {
e.printStackTrace(); if(chatCache == null){
} catch (Exception e) { throw(new Exception("chatCache初始化失败"));
e.printStackTrace(); }
} catch (Exception e) {
System.out.println(e.getMessage());
//e.printStackTrace();
} }
/** /**
...@@ -96,19 +107,18 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -96,19 +107,18 @@ public class GetAnswerServlet extends HttpServlet {
* 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据 * 如果读档失败,则开始新的游戏,读档失败的判断标准是除了初始化数据外没有其他任何数据
*/ */
historyInfoPoint = chatCache.getInfoPoint(); //historyInfoPoint = chatCache.getInfoPoint();
if(userinfo.varInitialMap.get("botType") != null)
botType = userinfo.varInitialMap.get("botType");
switch(botType){ switch(botType){
case "game": case "game":
WorldController worldController = new WorldController(logWriter,userinfo); WorldController worldController = new WorldController(logWriter,userinfo);
botUtil = new GameBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter, worldController, chatCache.getGameEnv(), chatCache); botUtil = new GameBotUtil(curInfoPoint, chatCache, userinfo, logWriter, worldController);
break; break;
default: default:
botUtil = new BasicBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter); botUtil = new BasicBotUtil(curInfoPoint, chatCache, userinfo, logWriter);
break; break;
} }
...@@ -117,10 +127,10 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -117,10 +127,10 @@ public class GetAnswerServlet extends HttpServlet {
//信息点预处理 //信息点预处理
ActionMatcher matcher = new ActionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil); ActionMatcher matcher = new ActionMatcher(curInfoPoint, logWriter, userinfo, context, botUtil);
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ /*得到答案更新信息点&生成答案,,清除超时会话数据, 转成json,输出*/
ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo);
if (state.equals("") && ansAction.getPriority()== -1) if (state.equals("") && ansAction.getPriority()== -1)
state = "我不理解,"; state = "我不理解,";
...@@ -129,24 +139,31 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -129,24 +139,31 @@ public class GetAnswerServlet extends HttpServlet {
bestMatch = matcher.getSolution(ansAction, context, userinfo); bestMatch = matcher.getSolution(ansAction, context, userinfo);
//读档成功不应该再激活
//if(matcher.) if(!botUtil.getChatCache().getReload()) {
if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) { //读档成功不应该再激活
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 //if(matcher.)
bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo);
}
}else{
//跳过
botUtil.getChatCache().setReload(false); //清楚标识
} }
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + historyInfoPoint.get("currentAction")); bestMatch = new Solution(0, " \n" + return_str + "\n " + state, "nextStep=" + botUtil.getChatCache().getInfoPoint().get("currentAction"));
} }
//针对不同游戏类型做后处理 //针对不同bot类型做后处理
botUtil.postprocessing(chatKey, context, bestMatch); botUtil.postprocessing(chatKey, context, bestMatch);
historyInfoPoint.put("lastReply", bestMatch.getAnswer()); botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer());
if (debugFlag) { if (debugFlag) {
matcher.appendDebugInfo(bestMatch, context); matcher.appendDebugInfo(bestMatch, context);
} }
...@@ -156,7 +173,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -156,7 +173,7 @@ public class GetAnswerServlet extends HttpServlet {
matcher.infoTransfer(bestMatch, context, debugFlag); matcher.infoTransfer(bestMatch, context, debugFlag);
ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache.getInfoPoint(), chatCache.getGameEnv(), context, userinfo); ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache, context, userinfo);
//清理超时的用户数据 //清理超时的用户数据
if (context.getAttribute("cacheUpdateTime") == null) if (context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
...@@ -172,6 +189,8 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -172,6 +189,8 @@ public class GetAnswerServlet extends HttpServlet {
ansJ = "找不到配置文件"; ansJ = "找不到配置文件";
} }
System.out.println(TEST_VAR);
logWriter.writeln(); logWriter.writeln();
......
package com.qiwu.chatbotbackend.task.utils; package com.qiwu.chatbotbackend.task.utils;
import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.Action;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.LogWriter;
...@@ -15,19 +16,23 @@ import java.util.regex.Pattern; ...@@ -15,19 +16,23 @@ import java.util.regex.Pattern;
public class BasicBotUtil { public class BasicBotUtil {
Map<String, String> curInfoPoint = null; Map<String, String> curInfoPoint = null;
Map<String, String> historyInfoPoint = null;
UserInfo userinfo = null; UserInfo userinfo = null;
LogWriter logWriter = null; LogWriter logWriter = null;
ChatCache chatCache = null;
public String botType = "basic";
public ChatCache getChatCache() {
return chatCache;
}
public BasicBotUtil(){}; public BasicBotUtil(){};
public BasicBotUtil(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, LogWriter logWriter){ public BasicBotUtil(Map<String, String> curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter){
this.curInfoPoint = curInfoPoint; this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint;
this.userinfo = userinfo; this.userinfo = userinfo;
this.logWriter = logWriter; this.logWriter = logWriter;
this.chatCache = chatCache;
} }
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
...@@ -36,7 +41,6 @@ public class BasicBotUtil { ...@@ -36,7 +41,6 @@ public class BasicBotUtil {
} }
//在接收到请求后对数据做处理,转化为系统可以处理的数据 //在接收到请求后对数据做处理,转化为系统可以处理的数据
/** /**
...@@ -104,18 +108,18 @@ public class BasicBotUtil { ...@@ -104,18 +108,18 @@ public class BasicBotUtil {
} }
String currentAction = ""; String currentAction = "";
if (historyInfoPoint.containsKey("currentAction")) if (chatCache.getInfoPoint().containsKey("currentAction"))
currentAction = historyInfoPoint.get("currentAction"); currentAction = chatCache.getInfoPoint().get("currentAction");
else if (userinfo.extraInfo.containsKey("activeAction")) { else if (userinfo.extraInfo.containsKey("activeAction")) {
currentAction = userinfo.extraInfo.get("activeAction"); currentAction = userinfo.extraInfo.get("activeAction");
historyInfoPoint.put("currentAction", currentAction); chatCache.getInfoPoint().put("currentAction", currentAction);
} else } else
currentAction = " "; currentAction = " ";
curInfoPoint.put("emptySet", " "); curInfoPoint.put("emptySet", " ");
if (historyInfoPoint.get("activeList") == null) { if (chatCache.getInfoPoint().get("activeList") == null) {
historyInfoPoint.put("activeList", currentAction); chatCache.getInfoPoint().put("activeList", currentAction);
} }
if (unknown_flag && !currentAction.equals("")) { if (unknown_flag && !currentAction.equals("")) {
...@@ -123,7 +127,7 @@ public class BasicBotUtil { ...@@ -123,7 +127,7 @@ public class BasicBotUtil {
curInfoPoint.put(currentAction, i); curInfoPoint.put(currentAction, i);
} }
logWriter.record("historyInfoPoint:" + historyInfoPoint.toString(), 1); logWriter.record("historyInfoPoint:" + chatCache.getInfoPoint().toString(), 1);
...@@ -131,8 +135,8 @@ public class BasicBotUtil { ...@@ -131,8 +135,8 @@ public class BasicBotUtil {
} }
public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){
if(historyInfoPoint.get("error_message") != null && historyInfoPoint.get("error_message") != ""){ if(chatCache.getInfoPoint().get("error_message") != null && chatCache.getInfoPoint().get("error_message") != ""){
bestMatch.setAnswer(bestMatch.getAnswer() + historyInfoPoint.get("error_message")); bestMatch.setAnswer(bestMatch.getAnswer() + chatCache.getInfoPoint().get("error_message"));
} }
...@@ -172,7 +176,7 @@ public class BasicBotUtil { ...@@ -172,7 +176,7 @@ public class BasicBotUtil {
* @param updateValue * @param updateValue
*/ */
public void putKeyword(String variableName, String updateValue){ public void putKeyword(String variableName, String updateValue){
historyInfoPoint.put(variableName, updateValue); chatCache.getInfoPoint().put(variableName, updateValue);
} }
public String knowledgeProcess(String variableName, String updateValue){ public String knowledgeProcess(String variableName, String updateValue){
...@@ -209,11 +213,11 @@ public class BasicBotUtil { ...@@ -209,11 +213,11 @@ public class BasicBotUtil {
reply = reply.replace("{" + variable + "-1}", keyword); reply = reply.replace("{" + variable + "-1}", keyword);
} }
} else if (m.group(1).endsWith("-2}")) { } else if (m.group(1).endsWith("-2}")) {
if (historyInfoPoint.get(variable) != null) if (chatCache.getInfoPoint().get(variable) != null)
if(historyInfoPoint.get(variable).equals("do_reset")){ if(chatCache.getInfoPoint().get(variable).equals("do_reset")){
reply = reply.replace("{" + variable + "-2}", ""); reply = reply.replace("{" + variable + "-2}", "");
}else }else
reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); reply = reply.replace("{" + variable + "-2}", chatCache.getInfoPoint().get(variable));
} }
} }
......
package com.qiwu.chatbotbackend.task.utils;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.processing.ChatCacheController;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
@WebListener
public class ContextDestroyListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("destory context....");
/**
* 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来
*/
String chatKey;
ServletContext servletContext = sce.getServletContext();
Object obj = servletContext.getAttribute("chatCache");
ChatCache cache = null;
SqlHelper helper = null;
if(obj != null){
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)obj;
Iterator<String> cacheIter = chatCacheMap.keySet().iterator();
try {
helper = new SqlHelper();
while (cacheIter.hasNext()) {
chatKey = cacheIter.next();
cache = chatCacheMap.get(chatKey);
//当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档
if (cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) {
System.out.println(String.format("saving %s", chatKey));
ChatCacheController.saveChatCache(cache, helper);
}
}
cacheIter.remove();
helper.destroy();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.qiwu.chatbotbackend.task.utils;
import com.qiwu.chatbotbackend.Config.ConfigInitializer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ContextInitialListener implements ServletContextListener {
String CONFIG_DIR = "config.txt";
/**
* 在程序初始化时,从配置文件中加载数据
* @param sce
*/
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Initial context....");
//Config config = new Config();
ConfigInitializer.init();
}
}
...@@ -5,18 +5,17 @@ import com.qiwu.chatbotbackend.processing.SimpleUtil; ...@@ -5,18 +5,17 @@ import com.qiwu.chatbotbackend.processing.SimpleUtil;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import static com.qiwu.chatbotbackend.Config.Config.CC_URL;
public class DataDeliver extends Thread { public class DataDeliver extends Thread {
JSONObject data = null; JSONObject data = null;
String url = ""; String url = CC_URL;
public void setData(JSONObject data) { public void setData(JSONObject data) {
this.data = data; this.data = data;
} }
public void setUrl(String url) {
this.url = url;
}
...@@ -25,7 +24,7 @@ public class DataDeliver extends Thread { ...@@ -25,7 +24,7 @@ public class DataDeliver extends Thread {
System.out.println("线程开始"); System.out.println("线程开始");
System.out.println(url); System.out.println(url);
try { try {
SimpleUtil.postJSON(url, data, null); SimpleUtil.postJSON(CC_URL, data, null);
System.out.println("线程完成"); System.out.println("线程完成");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
......
...@@ -7,6 +7,8 @@ import java.util.List; ...@@ -7,6 +7,8 @@ import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC1;
/** /**
* 实现一个支持通配符的基于广度优先算法的文件查找器 * 实现一个支持通配符的基于广度优先算法的文件查找器
*/ */
...@@ -88,7 +90,7 @@ public class FileFinder { ...@@ -88,7 +90,7 @@ public class FileFinder {
public static boolean deleteGameArchive(String baseDirName, String botAccount){ public static boolean deleteGameArchive(String baseDirName, String botAccount){
String tempName; String tempName;
String regEx = ".*@@@" + botAccount + "@@@@.*"; String regEx = ".*" + COMBINE_PUNC1 + botAccount + "-.*";
List fileList = new ArrayList(); List fileList = new ArrayList();
Pattern pattern = Pattern.compile(regEx); Pattern pattern = Pattern.compile(regEx);
Matcher matcher = null; Matcher matcher = null;
......
...@@ -4,7 +4,6 @@ import com.alibaba.fastjson.JSONObject; ...@@ -4,7 +4,6 @@ import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.entity.*;
import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.LogWriter;
import com.qiwu.chatbotbackend.processing.SimpleUtil; import com.qiwu.chatbotbackend.processing.SimpleUtil;
...@@ -17,32 +16,30 @@ import java.util.*; ...@@ -17,32 +16,30 @@ import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.*; import static com.qiwu.chatbotbackend.Config.Config.*;
import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER;
public class GameBotUtil extends BasicBotUtil{ public class GameBotUtil extends BasicBotUtil{
WorldController worldController = null; WorldController worldController = null;
GameEnv gameEnv = null;
ChatCache chatCache = null;
public static String LOAD_BY_SITE_CONDITION = "load_game_by_site"; public static String LOAD_BY_SITE_CONDITION = "load_game_by_site";
public static String LOAD_BY_LAST = "load_last"; public static String LOAD_BY_LAST = "load_last";
public GameBotUtil(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, UserInfo userinfo, LogWriter logWriter, WorldController worldController, GameEnv gameEnv, ChatCache chatCache){
this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint; public GameBotUtil(Map<String, String> curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter, WorldController worldController){
this.userinfo = userinfo; super(curInfoPoint, chatCache, userinfo, logWriter);
this.logWriter = logWriter;
this.gameEnv = gameEnv;
this.chatCache = chatCache;
this.worldController = worldController; this.worldController = worldController;
this.botType = "game";
} }
@Override @Override
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
Boolean debugFlag = infoPointPreprocessing(receiveParameters, context, false); Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false);
//将要去的地点的别名替换为真名 //将要去的地点的别名替换为真名
// String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; // String conditionList[] = {"yaobuyao", "want_know_zenmezuo"};
...@@ -66,11 +63,11 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -66,11 +63,11 @@ public class GameBotUtil extends BasicBotUtil{
// historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site")); // historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site"));
String activeList[] = historyInfoPoint.get("activeList").split("\\|"); String activeList[] = chatCache.getInfoPoint().get("activeList").split("\\|");
if(activeList.length == 0){ if(activeList.length == 0){
historyInfoPoint.put("临时变量condition", "yaobuyao"); chatCache.getInfoPoint().put("临时变量condition", "yaobuyao");
}else { }else {
historyInfoPoint.put("临时变量condition", activeList[activeList.length-1]); chatCache.getInfoPoint().put("临时变量condition", activeList[activeList.length-1]);
} }
...@@ -82,22 +79,22 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -82,22 +79,22 @@ public class GameBotUtil extends BasicBotUtil{
StringBuffer finalText = new StringBuffer(); StringBuffer finalText = new StringBuffer();
String plotText = bestMatch.getAnswer(); String plotText = SimpleUtil.randStr(bestMatch.getAnswer().split("~"));
//将自动跳转文本、qa文本、查询文本拼接 //将自动跳转文本、qa文本、查询文本拼接
String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text", "error_message"}; String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text", "error_message"};
String queryResult; String queryResult;
Set<String> keepNoSpeaker = new HashSet<String>(){ Set<String> keepNoSpeaker = new HashSet<String>(){
{ {
add("sendData:archiveList"); add("sendData:archiveList");
add("请说开始剧情或者继续剧情"); add(GAME_START_HINT);
} }
}; };
historyInfoPoint.put("plot_text", plotText); chatCache.getInfoPoint().put("plot_text", plotText);
//整合qa问答、地图、npc查询文本和剧情文本 //整合qa问答、地图、npc查询文本和剧情文本
for(String queryName:queryList){ for(String queryName:queryList){
queryResult = historyInfoPoint.get(queryName); queryResult = chatCache.getInfoPoint().get(queryName);
if(queryResult != null){ if(queryResult != null){
if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本 if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本
//剧情可以为空,其他不行 //剧情可以为空,其他不行
...@@ -116,7 +113,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -116,7 +113,7 @@ public class GameBotUtil extends BasicBotUtil{
case "goods_query": case "goods_query":
case "npc_query": case "npc_query":
case "error_message": case "error_message":
queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, historyInfoPoint, gameEnv); queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, chatCache.getInfoPoint(), chatCache.getGameEnv());
finalText.append(queryResult); finalText.append(queryResult);
break; break;
case "plot_text": case "plot_text":
...@@ -137,7 +134,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -137,7 +134,7 @@ public class GameBotUtil extends BasicBotUtil{
} }
historyInfoPoint.put(queryName, ""); chatCache.getInfoPoint().put(queryName, "");
} }
} }
...@@ -151,26 +148,29 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -151,26 +148,29 @@ public class GameBotUtil extends BasicBotUtil{
String keyword = ""; String keyword = "";
String nameSeries[] = actionName.split("_"); String nameSeries[] = actionName.split("_");
//变量名以npc_开头,就从游戏环境中查询相应的值 //变量名以npc_开头,就从游戏环境中查询相应的值
if(actionName.startsWith("npc_")){ if(actionName.startsWith("npc_")){
if(nameSeries.length == 4){ if(nameSeries.length == 4){
keyword = gameEnv.queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]); keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]);
}else if (nameSeries.length == 3){ }else if (nameSeries.length == 3){
if(nameSeries[1].equals("玩家") && nameSeries[2].equals("物品栏")) { if(nameSeries[1].equals("玩家") && nameSeries[2].equals("物品栏")) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
List<String> goods = gameEnv.queryGoodsByNpcName("玩家"); List<String> goods = chatCache.getGameEnv().queryGoodsByNpcName("玩家");
for (String good : goods) { for (String good : goods) {
sb.append("+").append(good); sb.append("+").append(good);
} }
keyword = sb.toString(); keyword = sb.toString();
}else{ }else{
keyword = gameEnv.queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]); keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]);
} }
} }
}else if (actionName.startsWith("goods_")) { }else if (actionName.startsWith("goods_")) {
nameSeries[2] = nameSeries[2].replace("所属角色", "owner"); if(nameSeries.length == 3) {
keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); nameSeries[2] = nameSeries[2].replace("所属角色", "owner");
keyword = chatCache.getGameEnv().queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]);
}
//System.out.println("return" + keyword); //System.out.println("return" + keyword);
...@@ -179,8 +179,8 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -179,8 +179,8 @@ public class GameBotUtil extends BasicBotUtil{
if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){ if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){
keyword = "not_exist"; keyword = "not_exist";
}else { }else {
logWriter.record("isNeighbour(" + historyInfoPoint.get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1); logWriter.record("isNeighbour(" + chatCache.getInfoPoint().get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1);
keyword = String.valueOf(gameEnv.isNeighbour(historyInfoPoint.get("site"), curInfoPoint.get(opPair[1]).split(":")[1])); keyword = String.valueOf(chatCache.getGameEnv().isNeighbour(chatCache.getInfoPoint().get("site"), curInfoPoint.get(opPair[1]).split(":")[1]));
logWriter.record("返回:" + keyword, 1); logWriter.record("返回:" + keyword, 1);
} }
}else { }else {
...@@ -217,15 +217,15 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -217,15 +217,15 @@ public class GameBotUtil extends BasicBotUtil{
updateValue = "update:" + updateValue; updateValue = "update:" + updateValue;
} }
variableName = variableName.replace("所属玩家", "owner"); variableName = variableName.replace("所属玩家", "owner");
String returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint); String returnStr = worldController.worldOperation(chatCache.getGameEnv(), variableName, updateValue, curInfoPoint, chatCache.getInfoPoint());
updateValue = returnStr; updateValue = returnStr;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
updateValue = "游戏模块处理出错"; updateValue = GAME_MODULE_ERROR;
} }
} }
historyInfoPoint.put(variableName, updateValue); chatCache.getInfoPoint().put(variableName, updateValue);
} }
...@@ -271,12 +271,12 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -271,12 +271,12 @@ public class GameBotUtil extends BasicBotUtil{
}else if (ansAction.getFeatureMap().containsKey("gameBackup")) { }else if (ansAction.getFeatureMap().containsKey("gameBackup")) {
System.out.println("gameBackup"); System.out.println("gameBackup");
chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint); chatCache = new ChatCache(userKey, randKey, chatCache.getGameEnv(), chatCache.getInfoPoint());
flag = ChatCacheController.saveChatCache(chatCache, null); flag = ChatCacheController.saveChatCache(chatCache, null);
if(flag) if(flag)
solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功");
else else
solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败");
} else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) { } else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) {
...@@ -306,7 +306,6 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -306,7 +306,6 @@ public class GameBotUtil extends BasicBotUtil{
System.out.println("sendArchiveList"); System.out.println("sendArchiveList");
DataDeliver dataDeliver = new DataDeliver(); DataDeliver dataDeliver = new DataDeliver();
dataDeliver.setUrl(userinfo.varInitialMap.get("CC_URL"));
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
List<ArchiveInfo> archiveList = helper.queryArchiveByUserKey(userKey); List<ArchiveInfo> archiveList = helper.queryArchiveByUserKey(userKey);
data.put("data", JSONObject.toJSON(archiveList)); data.put("data", JSONObject.toJSON(archiveList));
...@@ -334,11 +333,15 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -334,11 +333,15 @@ public class GameBotUtil extends BasicBotUtil{
ChatCache loadCache = null; ChatCache loadCache = null;
//如果存在读档,就要将自动跳转和qa的临时数据清空
historyInfoPoint.put("plot_jump_text", "");
historyInfoPoint.put("common_answer", "");
if (archiveInfo != null) { if (archiveInfo != null) {
//如果存在读档,就要将自动跳转和qa的临时数据清空
chatCache.getInfoPoint().put("plot_jump_text", "");
chatCache.getInfoPoint().put("common_answer", "");
try { try {
loadCache = ChatCacheController.loadChatCache(archiveInfo); loadCache = ChatCacheController.loadChatCache(archiveInfo);
} catch (Exception e) { } catch (Exception e) {
...@@ -346,6 +349,8 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -346,6 +349,8 @@ public class GameBotUtil extends BasicBotUtil{
solution.setAnswer("从本地加载存档失败"); solution.setAnswer("从本地加载存档失败");
e.printStackTrace(); e.printStackTrace();
} }
//this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint());
this.chatCache.setInfoPoint(loadCache.getInfoPoint()); this.chatCache.setInfoPoint(loadCache.getInfoPoint());
this.chatCache.setGameEnv(loadCache.getGameEnv()); this.chatCache.setGameEnv(loadCache.getGameEnv());
...@@ -354,8 +359,8 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -354,8 +359,8 @@ public class GameBotUtil extends BasicBotUtil{
System.out.println("----------读档中------------"); System.out.println("----------读档中------------");
site = loadCache.getInfoPoint().get("site"); site = loadCache.getInfoPoint().get("site");
String nextStep = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_CONDITION, site)); String nextStep = loadCache.getInfoPoint().get(String.format(TASK_CONDITION, site));
String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_REPLY, site)); String reply = loadCache.getInfoPoint().get(String.format(TASK_REPLY, site));
solution.setAnswer(reply); solution.setAnswer(reply);
solution.setNext("nextStep=" + nextStep); solution.setNext("nextStep=" + nextStep);
this.chatCache.setReload(true); this.chatCache.setReload(true);
...@@ -383,14 +388,14 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -383,14 +388,14 @@ public class GameBotUtil extends BasicBotUtil{
switch (varElements[0]){ switch (varElements[0]){
//如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。 //如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。
case "globalVariable": case "globalVariable":
reply = reply.replace(variableSlot, historyInfoPoint.get(variable)); reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable));
case "npc": case "npc":
result = gameEnv.queryNpcAttrByNpcName(varElements[1], varElements[2]); result = chatCache.getGameEnv().queryNpcAttrByNpcName(varElements[1], varElements[2]);
reply = reply.replace(variableSlot, result); reply = reply.replace(variableSlot, result);
case "goods": case "goods":
result = gameEnv.queryGoodsAttrByGoodsName(varElements[1], varElements[2]); result = chatCache.getGameEnv().queryGoodsAttrByGoodsName(varElements[1], varElements[2]);
reply = reply.replace(variableSlot, result); reply = reply.replace(variableSlot, result);
case "map": case "map":
...@@ -399,8 +404,8 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -399,8 +404,8 @@ public class GameBotUtil extends BasicBotUtil{
default: default:
if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){ if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){
reply = reply.replace(variableSlot, curInfoPoint.get(variable)); reply = reply.replace(variableSlot, curInfoPoint.get(variable));
}else if(historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")){ }else if(chatCache.getInfoPoint().get(variable) != null && !chatCache.getInfoPoint().get(variable).equals("")){
reply = reply.replace(variableSlot, historyInfoPoint.get(variable)); reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable));
} }
} }
...@@ -451,7 +456,9 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -451,7 +456,9 @@ public class GameBotUtil extends BasicBotUtil{
int flag = 1; int flag = 1;
if(m.find()) { if(m.find()) {
npc = m.group(1); npc = m.group(1);
location = gameEnv.queryNpcAttrByNpcName(npc, "location"); location = gameEnv.queryNpcAttrByNpcName(npc, "location");
System.out.println("location:" + location + ", npc:" + npc);
if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){
if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){
flag = 1; flag = 1;
...@@ -488,17 +495,17 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -488,17 +495,17 @@ public class GameBotUtil extends BasicBotUtil{
String location; String location;
Boolean flag = false; Boolean flag = false;
location = gameEnv.queryNpcAttrByNpcName(npc, "location"); location = chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "location");
if( location == null){ if( location == null){
return false; return false;
} }
if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){
if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ if(chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话") == null || chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话").equals("能")){
if(onlineDetect){ if(onlineDetect){
if(isOnlineMode(npc, historyInfoPoint)){ if(isOnlineMode(npc, chatCache.getInfoPoint())){
logWriter.record("\"" + npc + "\":匹配", 1); logWriter.record("\"" + npc + "\":匹配", 1);
flag = true; flag = true;
} }
...@@ -519,14 +526,14 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -519,14 +526,14 @@ public class GameBotUtil extends BasicBotUtil{
public static String appendTalker(String npc, String text, Map<String ,String> historyInfoPoint, GameEnv gameEnv){ public static String appendTalker(String npc, String text, Map<String ,String> historyInfoPoint, GameEnv gameEnv){
return String.format(TALKER_PATTERN, npc, PlotConstructor2.ASSISTANT_EMOTION) + text; return String.format(TALKER_PATTERN, npc, ASSISTANT_EMOTION) + text;
} }
String plotTextFilt(String reply){ String plotTextFilt(String reply){
String textType, returnText = "plot text filt error", plotLastTalker; String textType, returnText = "plot text filt error", plotLastTalker;
String site = historyInfoPoint.get("site"); String site = chatCache.getInfoPoint().get("site");
textType = textTypeDetect(reply, site); textType = textTypeDetect(reply, site);
...@@ -537,13 +544,13 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -537,13 +544,13 @@ public class GameBotUtil extends BasicBotUtil{
returnText = reply; returnText = reply;
break; break;
case "less_talker": case "less_talker":
return appendTalker(findRelateTalkers(false).get(0), reply, historyInfoPoint, gameEnv); return appendTalker(findRelateTalkers(false).get(0), reply, chatCache.getInfoPoint(), chatCache.getGameEnv());
case "to_unknown": case "to_unknown":
Set<String> candidates = new HashSet<String>(); Set<String> candidates = new HashSet<String>();
Map<String, List<String>> npcTextMap = null; Map<String, List<String>> npcTextMap = null;
String unknownList = "", foundNPC; String unknownList = "", foundNPC;
String fieldList[] = {"unknownTextList", "finalUnknownText"}; String fieldList[] = {"unknownTextList", "finalUnknownText"};
String lastReply = historyInfoPoint.get("lastReply"); String lastReply = chatCache.getInfoPoint().get("lastReply");
plotLastTalker = findTextLastTalker(lastReply, site); plotLastTalker = findTextLastTalker(lastReply, site);
...@@ -639,8 +646,8 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -639,8 +646,8 @@ public class GameBotUtil extends BasicBotUtil{
* includeSiteNPC 是否包含当前地点的npc * includeSiteNPC 是否包含当前地点的npc
*/ */
private List<String> findRelateTalkers(Boolean includeSiteNPC){ private List<String> findRelateTalkers(Boolean includeSiteNPC){
String site = historyInfoPoint.get("site"); String site = chatCache.getInfoPoint().get("site");
String lastReply = historyInfoPoint.get("lastReply"); String lastReply = chatCache.getInfoPoint().get("lastReply");
List<String> talkers = new ArrayList<String>(); List<String> talkers = new ArrayList<String>();
...@@ -653,7 +660,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -653,7 +660,7 @@ public class GameBotUtil extends BasicBotUtil{
} }
if(includeSiteNPC){ if(includeSiteNPC){
List<String> npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); List<String> npcList = chatCache.getGameEnv().queryAroundNpcBySite(chatCache.getInfoPoint().get("site"));
for(String npc:npcList){ for(String npc:npcList){
if(canTalk(npc, site, true)){ if(canTalk(npc, site, true)){
talkers.add(npc); talkers.add(npc);
...@@ -662,7 +669,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -662,7 +669,7 @@ public class GameBotUtil extends BasicBotUtil{
} }
if(talkers.size() == 0){ if(talkers.size() == 0){
talkers.add(historyInfoPoint.get(ASSISTANT)); talkers.add(chatCache.getInfoPoint().get(ASSISTANT));
} }
return talkers; return talkers;
......
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