From dff6f51875b1c906efb43718c191974b9653f246 Mon Sep 17 00:00:00 2001 From: hxw Date: Thu, 14 Mar 2019 15:37:10 +0800 Subject: [PATCH] 添加配置文件 --- config.properties | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ deploy.sh | 6 ++++++ gameconfig.txt | 1 + keywords.txt | 101 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ pom.xml | 178 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/Config/Config.java | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/Config/ConfigInitializer.java | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/db/C3p0Utils.java | 13 +++++++++++++ src/db/SqlHelper.java | 384 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------- src/entity/Action.java | 17 ++++++++++------- src/entity/ChatCache.java | 26 +++++++++++++++----------- src/entity/ConfigTermText.java | 528 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/gameDesign/CharacterConstructor.java | 147 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------- src/gameDesign/ElementConstructor.java | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------- src/gameDesign/GlobalVariableConstructor.java | 4 +++- src/gameDesign/ItemConstructor.java | 140 +++++++++++++++++++++++++++++++++++++++++--------------------------------------------------------------------------------------------------- src/gameDesign/ListeningConstructor.java | 12 ++++++------ src/gameDesign/MapConstructor.java | 459 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/gameDesign/PlotConstructor2.java | 272 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------------------------------------------- src/processing/ActionMatcher.java | 44 +++++++++----------------------------------- src/processing/ChatCacheController.java | 22 ++++++++++++---------- src/processing/ConditionTableController.java | 239 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/FormsPoster.java | 3 +++ src/processing/SimpleUtil.java | 2 +- src/processing/UserInfoController.java | 33 +++++++++++++++++++++------------ src/processing/WorldController.java | 156 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------- src/servlet/GameDesignServlet.java | 31 +++++++++++++++++++++++-------- src/servlet/GetAnswerServlet.java | 65 ++++++++++++++++++++++++++++++++++++++++++----------------------- src/task/utils/BasicBotUtil.java | 36 ++++++++++++++++++++---------------- src/task/utils/ContextDestroyListener.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/task/utils/ContextInitialListener.java | 30 ++++++++++++++++++++++++++++++ src/task/utils/DataDeliver.java | 9 ++++----- src/task/utils/FileFinder.java | 4 +++- src/task/utils/GameBotUtil.java | 119 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------- 34 files changed, 2305 insertions(+), 1204 deletions(-) create mode 100644 config.properties create mode 100755 deploy.sh create mode 100644 gameconfig.txt create mode 100644 keywords.txt create mode 100644 pom.xml create mode 100644 src/Config/Config.java create mode 100644 src/Config/ConfigInitializer.java create mode 100644 src/entity/ConfigTermText.java delete mode 100644 src/processing/ConditionTableController.java create mode 100644 src/task/utils/ContextDestroyListener.java create mode 100644 src/task/utils/ContextInitialListener.java diff --git a/config.properties b/config.properties new file mode 100644 index 0000000..ef5659e --- /dev/null +++ b/config.properties @@ -0,0 +1,99 @@ +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 diff --git a/deploy.sh b/deploy.sh new file mode 100755 index 0000000..2ccf068 --- /dev/null +++ b/deploy.sh @@ -0,0 +1,6 @@ +#!/bin/bash +mvn clean package -Ppro -Dmaven.test.skip=true +cd target +scp my-app.jar hz1:visualkm/chatbot-backend +cd .. + diff --git a/gameconfig.txt b/gameconfig.txt new file mode 100644 index 0000000..4f6b678 --- /dev/null +++ b/gameconfig.txt @@ -0,0 +1 @@ +{"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 diff --git a/keywords.txt b/keywords.txt new file mode 100644 index 0000000..6645063 --- /dev/null +++ b/keywords.txt @@ -0,0 +1,101 @@ + + +# ------------------------------------------------------------------------------ +# 格式 +# 意图|语义关系名字|关键词 +# 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 + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..438dd0f --- /dev/null +++ b/pom.xml @@ -0,0 +1,178 @@ + + + 4.0.0 + + com + chatbot + 0.0.1-SNAPSHOT + jar + + chatbot + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.1.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + com.alibaba + fastjson + 1.2.51 + + + org.apache.httpcomponents + httpclient + 4.5 + + + commons-lang + commons-lang + 2.5 + + + org.apache.tomcat + tomcat-dbcp + 9.0.12 + + + + + c3p0 + c3p0 + 0.9.1.2 + + + + + log4j + log4j + 1.2.17 + + + + mysql + mysql-connector-java + 5.0.7 + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.google.guava + guava + 18.0 + + + + org.skyscreamer + jsonassert + 1.5.0 + + + + + + + my-app + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + + -Xmx64m + + + + + + + src/main/resources + + + test/* + pro/* + dev/* + + + *.properties + + true + + + src/main/resources/${profiles.active} + + + + + + + + dev + + dev + dev + + + true + + + + + + test + + test + test + + + + + + pro + + pro + pro + + + + + + diff --git a/src/Config/Config.java b/src/Config/Config.java new file mode 100644 index 0000000..3da8bd0 --- /dev/null +++ b/src/Config/Config.java @@ -0,0 +1,111 @@ +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; + +} diff --git a/src/Config/ConfigInitializer.java b/src/Config/ConfigInitializer.java new file mode 100644 index 0000000..39d6d30 --- /dev/null +++ b/src/Config/ConfigInitializer.java @@ -0,0 +1,75 @@ +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 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) type, value.toUpperCase())); + } + } +} diff --git a/src/db/C3p0Utils.java b/src/db/C3p0Utils.java index 6d3cdbe..cccd088 100644 --- a/src/db/C3p0Utils.java +++ b/src/db/C3p0Utils.java @@ -14,6 +14,8 @@ public class C3p0Utils { //通过标识名来创建相应连接池 static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); + //通过标识名来创建相应连接池 + static ComboPooledDataSource dataSource2 = new ComboPooledDataSource("mysql2"); //从连接池中取用一个连接 public static Connection getConnection() throws SQLException { @@ -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 { if (rs != null) { diff --git a/src/db/SqlHelper.java b/src/db/SqlHelper.java index 4ddefaf..a3020ff 100644 --- a/src/db/SqlHelper.java +++ b/src/db/SqlHelper.java @@ -1,6 +1,8 @@ package com.qiwu.chatbotbackend.db; 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.gameDesign.ElementConstructor; @@ -10,6 +12,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import static com.qiwu.chatbotbackend.Config.Config.*; + public class SqlHelper { private Connection conn = null; /* @@ -33,55 +37,377 @@ public class SqlHelper { } } -/* - public boolean insertAction(QuestionKeyWord qkw){ - String sql = "insert into user_info (chat_key,action_name) values(?,?)"; - boolean b = false; + //----------------------------------------condition操作--------------------------------------------------------------- + //------------------------------------------------------------------------------------------------------------ + + + 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 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 queryActionTextList(int botId){ + String sql = "select actionText from chatbot_condition where botId= ?"; + String pre_name = ""; + List actionTextList = new ArrayList(); try{ PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1,qkw.getChatKey()); - ps.setString(2,qkw.getActionName()); - b = ps.execute(); - return b; - } catch(Exception e){ + ps.setInt(1,botId); + ResultSet rs = ps.executeQuery(); + while(rs.next()){ + actionTextList.add(rs.getString("actionText")); + } + + + + }catch(Exception e){ e.printStackTrace(); } - return b; + return actionTextList; } - public boolean updateAction(QuestionKeyWord qkw){ - String sql = "update user_info set action_name=? where chat_key=?"; - boolean b = false; + public Condition queryActiveCondition(int botId){ + Condition condition = null; + + String sql = "select * from chatbot_condition where active= 1"; + String pre_name = ""; + List actionTextList = new ArrayList(); try{ PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1,qkw.getActionName()); - ps.setString(2,qkw.getChatKey()); - b = ps.execute(); - return b; - } catch (SQLException e) { + 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")); + } + + + + }catch(Exception e){ e.printStackTrace(); } - return b; + return condition; } - public String queryActionByKey(String chat_key){ - String sql = "select * from user_info where chat_key= ?"; + + + public List queryConditionCategoriesById(int botId){ + String sql = "select categoryStr from chatbot_condition where botId= ?"; String pre_name = ""; + List categoryList = new ArrayList(); try{ PreparedStatement ps = conn.prepareStatement(sql); - ps.setString(1,chat_key); + ps.setInt(1,botId); ResultSet rs = ps.executeQuery(); - if(rs.next()) - return rs.getString("action_name"); + while(rs.next()){ + 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){ 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 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 queryConditionByCategory(String category){ + boolean b; + List conditionList = new ArrayList(); + 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 queryConditionByCategory(int botId, String category){ + boolean b; + List conditionList = new ArrayList(); + 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 conditionList = new ArrayList(); + 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 queryConditionAll(int botId){ + boolean b; + List conditionList = new ArrayList(); + 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 { C3p0Utils.close(_conn, _st, _rs); @@ -152,7 +478,7 @@ public class SqlHelper { return b; } catch (SQLException e) { - System.out.println("删除旧数据config失败"); + System.out.println(DELETE_OLD_CONFIG_TERM_ERROR); e.printStackTrace(); return false; } @@ -172,7 +498,7 @@ public class SqlHelper { return b; } catch (SQLException e) { - System.out.println("删除旧数据variable失败"); + System.out.println(DELETE_OLD_VARIABLE_ERROR); e.printStackTrace(); return false; } @@ -193,7 +519,7 @@ public class SqlHelper { return b; } catch (SQLException e) { - System.out.println("删除旧数据category失败"); + System.out.println(DELETE_OLD_CATEGORY_ERROR); e.printStackTrace(); return false; } diff --git a/src/entity/Action.java b/src/entity/Action.java index 4f4bf7f..a4ca8be 100644 --- a/src/entity/Action.java +++ b/src/entity/Action.java @@ -31,6 +31,7 @@ public class Action { //this.activePriority = priority; } + /** * * @param originAction 这个action的初始状态 @@ -50,15 +51,17 @@ public class Action { this.id = originAction.id; this.configName = originAction.configName; 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,那么。。 - if(baseAuxiliaryPriority > originAction.auxiliaryPriority) - this.auxiliaryPriority = baseAuxiliaryPriority; - else - this.auxiliaryPriority = originAction.auxiliaryPriority; + this.auxiliaryPriority = originAction.auxiliaryPriority + baseAuxiliaryPriority; //优先级为两者之和 +// //如果激活originAction的action,它的辅助优先级高于originAction,那么。。 +// if(baseAuxiliaryPriority > originAction.auxiliaryPriority) +// this.auxiliaryPriority = baseAuxiliaryPriority; +// else +// this.auxiliaryPriority = originAction.auxiliaryPriority; +// +// this.auxiliaryPriority = this.getAuxiliaryPriority() + 1; } public Action() { diff --git a/src/entity/ChatCache.java b/src/entity/ChatCache.java index 4da13e5..0bb4e75 100644 --- a/src/entity/ChatCache.java +++ b/src/entity/ChatCache.java @@ -92,25 +92,29 @@ public class ChatCache implements DisposableBean { public void destroy() throws IOException { } - public ChatCache(UserInfo userInfo, String userKey, String randKey) throws Exception { - try { - gameEnv = new GameEnv(userInfo.botAccount); - } catch (Exception e) { - System.out.println(ENV_ERROR); - - infoPoint.put("error_message", ENV_ERROR); - e.printStackTrace(); + public ChatCache(UserInfo userInfo, String userKey, String randKey, String botType) throws Exception { + + if(botType.equals("game")) { + try { + this.gameEnv = new GameEnv(userInfo.botAccount); + System.out.println("初始化时:" + this.gameEnv); + } catch (Exception e) { + System.out.println(ENV_ERROR); + + this.infoPoint.put("error_message", ENV_ERROR); + e.printStackTrace(); + } } String k; this.botAccount = userInfo.botAccount; - infoPoint = new HashMap(); + this.infoPoint = new HashMap(); Iterator iit = userInfo.varInitialMap.keySet().iterator(); while (iit.hasNext()) { 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.userKey = userKey; diff --git a/src/entity/ConfigTermText.java b/src/entity/ConfigTermText.java new file mode 100644 index 0000000..2a2dfa2 --- /dev/null +++ b/src/entity/ConfigTermText.java @@ -0,0 +1,528 @@ +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 iterNum=new ThreadLocal() { + 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 statusMap = new HashMap() { + { + 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 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 curPremise, List hisPremise, Map 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 premises, String extraPremise) { + StringBuffer sb = new StringBuffer(); + String premiseStr = "", conditionName; + Map nameCount = new HashMap(); + + 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 knowledge, String extraKL) { + StringBuffer sb = new StringBuffer(); + String varName = "", varValue = "", knowledgeStr; + Iterator 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 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 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 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 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 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; + } +} diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java index 9936164..178b608 100644 --- a/src/gameDesign/CharacterConstructor.java +++ b/src/gameDesign/CharacterConstructor.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; @@ -25,46 +25,36 @@ public class CharacterConstructor extends ElementConstructor { try { - String pattern1 = keywordMap.get("npc_location_pattern").toString(); + //FIND_NPC_LOCATION + String pattern; StringBuffer onlineModeTalkers = new StringBuffer(","); - JSONArray allNPC = gameElements.getJSONArray("npc"); Map attribute = null; HashSet classSet = new HashSet(); + List replaceList = new ArrayList(); - 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 @@ -79,8 +69,9 @@ public class CharacterConstructor extends ElementConstructor { appendPOS(POS, name, "人名"); 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")){ @@ -88,8 +79,10 @@ public class CharacterConstructor extends ElementConstructor { if(!nickname.equals("")) { appendPOS(POS, 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 { //添加类名称 if (!classSet.contains(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); + //替换后的名字改为npc名 + replaceList.get(0)[1] = name; + replaceList.add(new String[]{"attrName", ""}); + for(String attrName:attribute.keySet()){ + replaceList.get(1)[1] = attrName; appendPOS(POS, attrName, "名词"); for(String NPCName:nameList) { - - - for (String condition : attrRelateConditions) { - keywordMap.get("npc_" + condition).append("+").append(NPCName).append(":").append(attrName); - } + appendReplacedKeyword("NPC_ATTR", replaceList); } } } + + replaceList.add(new String[]{"botName", botName}); + appendReplacedKeyword("WHO_YOU_ARE", replaceList); + + keywordMap.put("onlineModeTalkers", onlineModeTalkers); varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString()); - //System.out.println("onlineModeTalkers" + varInitialMap.get("onlineModeTalkers")); 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的名字查询地点 - for (String conditionName : locationRelateConditions) { - 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); - } + queryTypeConfigTermGenerate(keywordMap, "NPC_LOCATION", "npc", "queryLocationByConditionName"); //根据根据NPC名字和属性查询属性值 - for(String conditionName: attrRelateConditions){ - configTerm = new ConfigTerm( - conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ", - "match,return-0", "", "yaobuyao", - "npc_query:queryAttrByNPCName:" + conditionName - ); - ConfigTerm.activateCopy(configTerm, configTermList, "npc"); - } + queryTypeConfigTermGenerate(keywordMap, "NPC_ATTR", "npc", "queryAttrByNPCName"); //根据根据NPC类别和地点属性查询所有NPC实例 - for (String conditionName : classRelateConditions) { - - 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); - } + + queryTypeConfigTermGenerate(keywordMap, "AOURND_NPC_CLASS", "npc", "queryAroundNpcByClassName"); + //根据类名查询周围所有实例 - 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"); - } - //查询说话的人 - 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"); - } + queryTypeConfigTermGenerate(keywordMap, "HOW_FIND_NPC", "npc", "queryFindNPCWay"); + //查询说话的人 + //WHO_YOU_ARE + queryTypeConfigTermGenerate(keywordMap, "WHO_YOU_ARE", "npc", "queryLastTalker"); }catch (Exception e){ operationStatus = 0; @@ -197,5 +162,9 @@ public class CharacterConstructor extends ElementConstructor { e.printStackTrace(); return; } + + } + + } diff --git a/src/gameDesign/ElementConstructor.java b/src/gameDesign/ElementConstructor.java index dc83cd0..753f4b3 100644 --- a/src/gameDesign/ElementConstructor.java +++ b/src/gameDesign/ElementConstructor.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; @@ -19,8 +19,7 @@ public class ElementConstructor { Map keywordMap = null; SqlHelper helper = null; HashSet exceptRelation = null; - ConfigTerm configTerm = null; - String CHITCHAT_URL = "http:192.168.1.178:1111/test"; + ConfigTermText configTermText = null; String botAccount; @@ -29,7 +28,7 @@ public class ElementConstructor { List configDataList = new ArrayList(); - List configTermList = new ArrayList(); + List configTermTextList = new ArrayList(); StringBuffer configText = new StringBuffer(); Map varInitialMap = new HashMap(); Map conditionDescription = new HashMap(); @@ -46,8 +45,8 @@ public class ElementConstructor { public void construct(JSONObject gameElements, UserInfo userinfo) { } - public List getConfigTermList() { - return configTermList; + public List getConfigTermTextList() { + return configTermTextList; } public Map getConditionDescription() { @@ -66,16 +65,19 @@ public class ElementConstructor { return configText.toString(); } + //生成完整的后台配置文件 public void generateConfigText(List idList) { int id, length = idList.size(); String varValue; - ConfigTerm configTerm = null; + ConfigTermText configTermText = null; for (int i = 0; i < length; i++) { - configTerm = configTermList.get(i); + configTermText = configTermTextList.get(i); id = idList.get(i); - configText.append(configTerm.toString() + id + "\n"); + configText.append(configTermText.toString() + id + "\n"); } + + //变量 for (String varName : varInitialMap.keySet()) { varValue = varInitialMap.get(varName); configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n"); @@ -83,6 +85,14 @@ public class ElementConstructor { } + + /** + * 从生成的配置文件的获取哪些condition需要哪些关键词,然后用于生成condition + * @param config + * @param relationKeywords + * @param exceptRelation + * @param botName + */ public void parseKeyword(JSONObject config, Map> relationKeywords, HashSet exceptRelation, String botName){ String conditionName, pair[]; for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){ @@ -92,11 +102,13 @@ public class ElementConstructor { if(!exceptRelation.contains(conditionName)) { + //初始化 if(!relationKeywords.containsKey(conditionName + "_head")) { relationKeywords.put(conditionName + "_head", new HashSet()); relationKeywords.put(conditionName + "_tail", new HashSet()); } + //visitorname和bot的替换 premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); for (String keyword : ((String) premise.get("keywords")).split("\\+")) { @@ -106,6 +118,7 @@ public class ElementConstructor { } else if(keyword.contains(":")){ + //有些配置条目要求三元组两边的值都匹配,需要把两边的值分别加入题头和值域 pair = keyword.split(":",2); if(pair[1].equals("")) @@ -133,6 +146,7 @@ public class ElementConstructor { if(!exceptRelation.contains(conditionName)) { + if(!relationKeywords.containsKey(conditionName + "_head")) { relationKeywords.put(conditionName + "_head", new HashSet()); relationKeywords.put(conditionName + "_tail", new HashSet()); @@ -189,4 +203,57 @@ public class ElementConstructor { } } + + public void queryTypeConfigTermGenerate(Map 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 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); + } + + + } + } diff --git a/src/gameDesign/GlobalVariableConstructor.java b/src/gameDesign/GlobalVariableConstructor.java index f1d39f0..07a793a 100644 --- a/src/gameDesign/GlobalVariableConstructor.java +++ b/src/gameDesign/GlobalVariableConstructor.java @@ -8,6 +8,8 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import static com.qiwu.chatbotbackend.Config.Config.CC_URL; + public class GlobalVariableConstructor extends ElementConstructor { public GlobalVariableConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { @@ -40,7 +42,7 @@ public class GlobalVariableConstructor extends ElementConstructor { varInitialMap.put("botType", "game"); varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList")); 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"); diff --git a/src/gameDesign/ItemConstructor.java b/src/gameDesign/ItemConstructor.java index 3882487..b5a01ba 100644 --- a/src/gameDesign/ItemConstructor.java +++ b/src/gameDesign/ItemConstructor.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; @@ -26,7 +26,7 @@ public class ItemConstructor extends ElementConstructor { public void construct(JSONObject gameElements, UserInfo userinfo) { try { - String pattern1 = keywordMap.get("item_location_pattern").toString(); + String pattern; String category, name, className, description, attrValue; JSONArray goods = gameElements.getJSONArray("goods"); Map attribute = null; @@ -34,34 +34,19 @@ public class ItemConstructor extends ElementConstructor { HashSet classSet = new HashSet(); - keywordMap.putIfAbsent("item_wenzainali", new StringBuffer()); - keywordMap.putIfAbsent("item_shishenme", new StringBuffer()); - keywordMap.putIfAbsent("item_know_exist_what", new StringBuffer()); - keywordMap.putIfAbsent("item_nums", new StringBuffer()); - keywordMap.putIfAbsent("item_want_know_zenmezuo", new StringBuffer()); + copyPattern("HOW_FIND_ITEM"); + copyPattern("ITEM_LOCATION"); + copyPattern("AROUND_ITEM_CLASS"); + copyPattern("ITEM_ATTR"); - - //与物品属性查询相关的所有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(); + List replaceList = new ArrayList(); for (JSONObject good : goods.toJavaList(JSONObject.class)) { name = (String) good.get("name"); + replaceList.clear(); + replaceList.add(new String[]{"name", name}); + List nameList = new ArrayList(); nameList.add(name); @@ -69,16 +54,18 @@ public class ItemConstructor extends ElementConstructor { className = (String) good.get("class"); appendPOS(POS, name, "名词"); 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")){ for(String nickname:JSONArray.parseArray(good.getJSONArray("nickname").toJSONString(), String.class)){ if(!nickname.equals("")) { appendPOS(POS, nickname, "名词"); nameList.add(nickname); - keywordMap.get("item_want_know_zenmezuo").append(findPattern.replace("name", nickname)); - keywordMap.get("item_" + locationRelateConditions[0]).append(pattern1.replace("name", nickname)); + replaceList.get(0)[1] = nickname; + appendReplacedKeyword("ITEM_LOCATION", replaceList); + appendReplacedKeyword("HOW_FIND_ITEM", replaceList); } } } @@ -86,97 +73,52 @@ public class ItemConstructor extends ElementConstructor { //添加类名称 if (!classSet.contains(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); - 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, "名词"); - for(String itemName:nameList) { - for (String condition : attrRelateConditions) { - keywordMap.get("item_" + condition).append("+" + itemName + ":" + attrName); - } - } +// for(String itemName:nameList) { +// 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 - for(String conditionName: locationRelateConditions){ - configTerm = new ConfigTerm( - conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString() + "," + - "zainali::match-Keyword=" + keywordMap.get("map_zainali").toString(), " ", - "match,return-0", - "", - " ", - "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"); + configTermText = new ConfigTermText( + "zainali::match-Include=" + keywordMap.get("WHERE_I_AM_zainali") + "," + + "wenzainali::match-Keyword=" + keywordMap.get("ITEM_LOCATION_wenzainali").toString(), " ", + "match,return-0", "", "yaobuyao", "goods_query:queryLocationByConditionName:wenzainali" + ); + ConfigTermText.activateCopy(configTermText, configTermTextList, "item"); - } - //根据根据物品名字和属性查询属性值 - 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_LOCATION", "goods", "queryLocationByConditionName"); + //根据根据物品名字和属性查询属性值 + queryTypeConfigTermGenerate(keywordMap, "ITEM_ATTR", "goods", "queryAttrByGoodsName"); //根据类名查询周围所有实例 - for (String conditionName : attrRelateConditions) { - configTerm = new ConfigTerm( - conditionName + "::match-Include=" + classKeywords, " ", - "match,return-0", - "", - " ", - "goods_query:queryAroundGoodsByClassName:" + conditionName - ); - ConfigTerm.activateCopy(configTerm, configTermList, "item"); - } - + queryTypeConfigTermGenerate(keywordMap, "AROUND_ITEM_CLASS", "goods", "queryAroundGoodsByClassName"); //根据类名查询周围所有实例 - for (String conditionName : ownRelateConditions) { - 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, "WHAT_ITEM_I_HAVE", "goods", "queryPlayerItems"); - //根据类名查询周围所有实例 - 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"); - } + queryTypeConfigTermGenerate(keywordMap, "HOW_FIND_ITEM", "goods", "queryFindItemWay"); } catch(Exception e){ operationStatus = 0; diff --git a/src/gameDesign/ListeningConstructor.java b/src/gameDesign/ListeningConstructor.java index fd81405..99cba08 100644 --- a/src/gameDesign/ListeningConstructor.java +++ b/src/gameDesign/ListeningConstructor.java @@ -3,13 +3,13 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.Premise; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; -import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.*; +import static com.qiwu.chatbotbackend.Config.Config.*; public class ListeningConstructor extends ElementConstructor{ @@ -30,7 +30,7 @@ public class ListeningConstructor extends ElementConstructor{ } - public static void cc(String botAccount, JSONObject gameELments, HashMap plotIndex, List configTermList){ + public static void cc(String botAccount, JSONObject gameELments, HashMap plotIndex, List configTermTextList){ int size = 0; String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority; String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep; @@ -70,7 +70,7 @@ public class ListeningConstructor extends ElementConstructor{ if(nextCondition == null || nextCondition.equals("")){ - nextCondition = "yaobuyao"; + nextCondition = DEFAULT_CONDITION; } if(autoJump){ @@ -108,7 +108,7 @@ public class ListeningConstructor extends ElementConstructor{ feature = "match,return-0"; } - ConfigTerm configTerm = new ConfigTerm( + ConfigTermText configTermText = new ConfigTermText( curPremiseList, hisPremiseList, updateKnowledge, @@ -116,7 +116,7 @@ public class ListeningConstructor extends ElementConstructor{ ); System.out.println("生成:" + curPremiseList.get(0)); - configTermList.add(configTerm); + configTermTextList.add(configTermText); } } diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index a81d7ab..ab1a547 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -3,14 +3,17 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.UserInfo; 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 { - String nickname = "qiwu"; int[][] matrix; int locationNum; HashMap id2j = new HashMap(); @@ -50,7 +53,7 @@ public class MapConstructor extends ElementConstructor { keywordMap.get("site_list").append("+").append(locationName); - taskLineName = String.format(PlotConstructor2.TASK_LINE, locationName); + taskLineName = String.format(TASK_LINE, locationName); if (!varInitialMap.containsKey(taskLineName)) { @@ -109,56 +112,7 @@ public class MapConstructor extends ElementConstructor { Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), 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 { constructGreph(locations); //用弗洛伊德算法求最短路径 - Floyd floyd = new Floyd(); - floyd.findShortestPath(matrix, locationNum); - floyd.printPath(matrix, locationNum); - generateWantToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateWhereIam(gameElements, userName, keywordMap); - generateHowToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); - generateSurroundingItem(keywordMap); - generateSurroundingPeople(keywordMap); - generateSurroundThings(keywordMap); - generateSurroundPlace(keywordMap); - generateWeHave(keywordMap); - generateInnerPeople(keywordMap); - generateTaskDescription(keywordMap); + //Floyd floyd = new Floyd(); + //floyd.findShortestPath(matrix, locationNum); + //floyd.printPath(matrix, locationNum); + generateWantToThere(gameElements, keywordMap); + generateHowToThere(gameElements, keywordMap); + + //查询类型配置条目的生成 + queryTypeConfigTermGenerate(keywordMap, "WHERE_I_AM", "map", "queryWhereIam"); + queryTypeConfigTermGenerate(keywordMap, "WHERE_CAN_I_GO", "map", "queryCanGoBySite"); + queryTypeConfigTermGenerate(keywordMap, "AROUND_NPC", "map", "queryAroundNpcBySite"); + queryTypeConfigTermGenerate(keywordMap, "AROUND_ITEM", "map", "queryAroundGoodsBySite"); + queryTypeConfigTermGenerate(keywordMap, "AROUND_THINGS", "map", "queryAroundAllBySite"); + + 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){ @@ -198,129 +156,107 @@ public class MapConstructor extends ElementConstructor { } - /** - * 生成‘我在哪里’所需要的配置文件 - */ - public void generateWhereIam(JSONObject gameElements, String botAccount, Map 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 keywordMap) { - String conditionName = "want_know_zenmezuo"; + public void generateHowToThere(JSONObject gameElements, Map keywordMap) { + //String conditionName = "want_know_zenmezuo"; + String intent = "HOW_TO_THERE", placeA, keywordPattern, gotoSite; + String conditionNameList[] = keywordMap.get(intent).toString().split(","); StringBuffer placeKeywords = new StringBuffer(); String nameSet; - for (int i = 0; i < locationNum; i++) { - nameSet = (String) locations.getJSONObject(i).get("nameSet"); - placeKeywords.append("+").append(nameSet); - } + for(String conditionName:conditionNameList) { + placeKeywords.setLength(0); + 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"); - /** - * 生成‘我能去哪里’所需要的配置文件 - */ - public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { - String conditionName = "choose_gowhere"; - String conditionKeywords = keywordMap.get("map_" + conditionName).toString(); + configTermText = new ConfigTermText( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", + " ", + "match,return-0", + "", + " ", + "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 keywordMap) { - String placeA, placeB, descriptionB, text, pathNode, lastTaskCondition, lastTaskReply, taskLine; - String conditionName = "yaobuyao"; - String conditionKeywords = "地点"; - String start = (String) gameElements.get("start"); - String placeKeywords; + public void generateWantToThere(JSONObject gameElements, Map keywordMap) { + String placeA, lastTaskCondition, lastTaskReply, taskLine; + String intent = "GO_TO", keywordPattern; + String conditionName = keywordMap.get(intent).toString().split(",")[0]; + + keywordPattern = keywordMap.get(intent + "_" + conditionName).toString(); //包含去xx的所有地点的关键词集合 StringBuffer toAllSiteskeywords = new StringBuffer(); @@ -329,30 +265,29 @@ public class MapConstructor extends ElementConstructor { StringBuffer toSitekeywords = new StringBuffer(); - String goRelateConditions[] = {"yaobuyao"}; - String gotoMapptern = keywordMap.get("map_" + goRelateConditions[0]).toString(), gotoSite = ""; + String gotoSite = ""; for (int i = 0; i < locationNum; i++) { toSitekeywords.setLength(0); placeA = (String) locations.getJSONObject(i).get("name"); - gotoSite = gotoMapptern.replace("name", placeA); + gotoSite = keywordPattern.replace("name", placeA); toAllSiteskeywords.append(gotoSite); toSitekeywords.append(gotoSite); for (String nickname : name2nickname.get(placeA)) { - gotoSite = gotoMapptern.replace("name", nickname); + gotoSite = keywordPattern.replace("name", nickname); toAllSiteskeywords.append(gotoSite); toSitekeywords.append(gotoSite); } - lastTaskCondition = String.format(PlotConstructor2.TASK_CONDITION, placeA); - lastTaskReply = String.format(PlotConstructor2.TASK_REPLY, placeA); - taskLine = String.format(PlotConstructor2.TASK_LINE, placeA); + lastTaskCondition = String.format(TASK_CONDITION, placeA); + lastTaskReply = String.format(TASK_REPLY, placeA); + taskLine = String.format(TASK_LINE, placeA); //地点任务和地点回答的初始化 if (!varInitialMap.containsKey(lastTaskCondition)) { - varInitialMap.put(lastTaskCondition, goRelateConditions[0]); + varInitialMap.put(lastTaskCondition, conditionName); varInitialMap.put(lastTaskReply, script.get("SITE_NOT_ACTIVE").replace("[地点名]", placeA)); conditionDescription.put(lastTaskCondition, lastTaskCondition); conditionDescription.put(lastTaskReply, lastTaskReply); @@ -362,37 +297,39 @@ public class MapConstructor extends ElementConstructor { /** * 要去某个地方,并且该地点相邻或者可以直接到达 */ - conditionName = goRelateConditions[0]; - configTerm = new ConfigTerm( + configTermText = new ConfigTermText( conditionName + "::match-Include=" + toSitekeywords + "," + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", " ", "match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_" + placeA + "_*", "" ); - configTerm.setConfigName("map", true); - configTermList.add(configTerm); + configTermText.setConfigName("map", true); + configTermTextList.add(configTermText); - //上一个配置文件激活时的默认选项 - configTerm = new ConfigTerm( + //上一个配置文件激活时的默认选项(兜底),上一条一定会激活下一条,下一条是没有条件的,如果没有找到其他可以激活的配置条目,则激活下一条 + configTermText = new ConfigTermText( " ", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA + "-<-npc_update:updateFollowerLocation:" + placeA + "-<-game_step:var={" + taskLine + "-2}" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("plot_" + placeA + "_doudi", false); - configTerm.setjStatus(1); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("plot_" + placeA + "_doudi", false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + //上一个配置文件激活时的默认选项, 地点任务线未开启,则不更新game_step - configTerm = new ConfigTerm( + configTermText = new ConfigTermText( lastTaskCondition + "::match-Include=null", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA + "-<-npc_update:updateFollowerLocation:" + placeA ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("plot_" + placeA + "_doudi2", false); - configTerm.setjStatus(1); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("plot_" + placeA + "_doudi2", false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); } @@ -400,7 +337,7 @@ public class MapConstructor extends ElementConstructor { /** * 要去的地方就在当前地点 */ - configTerm = new ConfigTerm( + configTermText = new ConfigTermText( conditionName + "::match-Include=" + toAllSiteskeywords + ",isNeighbour:" + conditionName + "::match-Include=0", " ", @@ -409,14 +346,14 @@ public class MapConstructor extends ElementConstructor { " ", "map_query:queryPathAt:" ); - configTerm.setConfigName("map", true); - configTermList.add(configTerm); + configTermText.setConfigName("map", true); + configTermTextList.add(configTermText); /** * 要去的地方要经过几个地点才能到达 */ - configTerm = new ConfigTerm( + configTermText = new ConfigTermText( conditionName + "::match-Include=" + toAllSiteskeywords + ",isNeighbour:" + conditionName + "::match-Include=2", " ", @@ -425,13 +362,13 @@ public class MapConstructor extends ElementConstructor { " ", "map_query:queryToDoPathBySite:" + conditionName ); - configTerm.setConfigName("map", true); - configTermList.add(configTerm); + configTermText.setConfigName("map", true); + configTermTextList.add(configTermText); /** * 要去的地方不可到达 */ - configTerm = new ConfigTerm( + configTermText = new ConfigTermText( conditionName + "::match-Include=" + toAllSiteskeywords + ",isNeighbour:" + conditionName + "::match-Include=5", " ", @@ -440,152 +377,8 @@ public class MapConstructor extends ElementConstructor { " ", "map_query:queryPathNotExist:" ); - configTerm.setConfigName("map", true); - configTermList.add(configTerm); - - - } - - - - /** - * 生成‘周围有什么人’所需要的配置文件 - */ - public void generateSurroundingPeople(Map 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 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 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"); + configTermText.setConfigName("map", true); + configTermTextList.add(configTermText); } - - - /** - * 生成‘周围有什么地点’所需要的配置文件 - */ - public void generateSurroundPlace(Map 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 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 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 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 diff --git a/src/gameDesign/PlotConstructor2.java b/src/gameDesign/PlotConstructor2.java index cd5003c..a1e084c 100644 --- a/src/gameDesign/PlotConstructor2.java +++ b/src/gameDesign/PlotConstructor2.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.Premise; import com.qiwu.chatbotbackend.entity.UserInfo; @@ -12,15 +12,11 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static com.qiwu.chatbotbackend.Config.Config.*; -public class PlotConstructor2 extends ElementConstructor { - public static String ASSISTANT = "globalVariable_智能助手"; - public static String ASSISTANT_EMOTION = "正常"; - public static String TASK_DESCRIPTION = "globalVariable_任务"; +public class PlotConstructor2 extends ElementConstructor { - public static String TALKER_PATTERN = "【%s@%s】"; - public static String GAME_STEP_FORMAT = "%s_plot_%s"; JSONArray plots = null; HashMap> adjList = new HashMap>(); @@ -32,10 +28,6 @@ public class PlotConstructor2 extends ElementConstructor { 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 keywordMap, HashSet exceptRelation, StringBuffer POS) { super(); @@ -62,7 +54,8 @@ public class PlotConstructor2 extends ElementConstructor { constructAdjList(plots); 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); if(jsonObject.get("firstUnknownText") == null) @@ -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"))); - conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); - conditionDescription.put("game_step", "QA问答游戏进度"); + conditionDescription.put("unknownText", UNKNOWN_TEXT_DESCRIPTION); + conditionDescription.put("game_step", GAME_STEP_DESCRIPTION); BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); varInitialMap.put(start, "1"); - ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermList); + ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermTextList); } else { - System.out.println("start剧情不存在"); + System.out.println(START_PLOT_NOT_EXIST); operationStatus = 0; - message = "开始剧情不存在,请到剧情列表设置"; + message = START_PLOT_NOT_EXIST; return; } } catch(Exception e){ operationStatus = 0; - message = "剧情接口处理出现异常"; + message = PLOT_GENERATION_ERROR; e.printStackTrace(); return; } @@ -167,7 +160,7 @@ public class PlotConstructor2 extends ElementConstructor { public static void varSlotFilt(JSONObject plot, Map keywordMap){ 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); Matcher m = replacePattern.matcher(plot.getString("plotText")); while (m.find()) { @@ -193,7 +186,7 @@ public class PlotConstructor2 extends ElementConstructor { * @param userinfo */ 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; String hint, gameStep, nextGameStep; JSONObject node = null, branchNode = null; @@ -215,16 +208,16 @@ public class PlotConstructor2 extends ElementConstructor { if(root.get("conditionName") != null && !root.get("conditionName").equals("")) conditionName = (String)root.get("conditionName"); else{ - conditionName = "yaobuyao"; + conditionName = DEFAULT_CONDITION; root.put("conditionName", conditionName); } String startPlace = ((String)root.get("place")).split("\\+")[0]; - String startTaskLine = String.format(PlotConstructor2.TASK_LINE, startPlace); - String startTaskCondition = String.format(PlotConstructor2.TASK_CONDITION, startPlace); - String startTaskReply = String.format(PlotConstructor2.TASK_REPLY, startPlace); + String startTaskLine = String.format(TASK_LINE, startPlace); + String startTaskCondition = String.format(TASK_CONDITION, startPlace); + String startTaskReply = String.format(TASK_REPLY, startPlace); varInitialMap.put("site", startPlace); varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId)); varInitialMap.put(startTaskCondition, ""); @@ -239,7 +232,7 @@ public class PlotConstructor2 extends ElementConstructor { Queue queue = new LinkedList(); queue.add(root); - System.out.println(root.toJSONString()); + //System.out.println(root.toJSONString()); while (!queue.isEmpty()) { node = queue.remove(); @@ -249,8 +242,8 @@ public class PlotConstructor2 extends ElementConstructor { curAutoJump = node.getBoolean("autoJump"); prevAutoJump = node.getBoolean("prevAutoJump"); curUnknownText = (String) node.get("unknownText"); - taskLineName = String.format(PlotConstructor2.TASK_LINE, location); - conditionDescription.put(id, "剧情" + id + "状态"); + taskLineName = String.format(TASK_LINE, location); + conditionDescription.put(id, String.format(PLOT_STATUS, id)); varInitialMap.put(id ,""); //本任务线的最后一个condition和本任务线的最后一个回答 @@ -307,7 +300,7 @@ public class PlotConstructor2 extends ElementConstructor { //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 nextCondition = plotIndex.get(nextId).getString("conditionName"); if(nextCondition.equals("")) - nextCondition = "yaobuyao"; + nextCondition = DEFAULT_CONDITION; nextLocation = plotIndex.get(nextId).getString("place"); @@ -357,7 +350,7 @@ public class PlotConstructor2 extends ElementConstructor { } - System.out.println(id); + //System.out.println(id); appendFeature(extraFT, "match"); //下一步为自动跳转且地点相同,则将回答放在plot_jump_text @@ -433,7 +426,8 @@ public class PlotConstructor2 extends ElementConstructor { if(curUnknownText.equals("")) { //如果没有unknown,就提示他到下一个地点 - hint = "请到" + nextLocation; + hint = String.format(LOCATION_HINT, nextLocation); + //hint = "请到" + nextLocation; //如果当前地点和下一步剧情地点不同,要提示 }else { //如果有unknown,就提示unknown文本 @@ -484,14 +478,14 @@ public class PlotConstructor2 extends ElementConstructor { nextCondition = "plot_" + nextId; } - configTerm = new ConfigTerm( + configTermText = new ConfigTermText( curPremiseList, historyPremiseList, updateKnowledge, "", extraHP.toString(), extraUK.toString(), extraFT.toString(), reply, nextCondition, "1" ); - configTerm.setConfigName("plot_" + id, false); + configTermText.setConfigName("plot_" + id, false); //当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转 @@ -499,11 +493,11 @@ public class PlotConstructor2 extends ElementConstructor { Boolean activateFlag = false; if(extraFT.indexOf("activate") != -1) activateFlag = true; - unconditionalPlotProcess(configTerm, nextCondition, activateFlag); + unconditionalPlotProcess(configTermText, nextCondition, activateFlag); } if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) - configTerm.setAuxiliaryPriority("3"); - configTermList.add(configTerm); + configTermText.setAuxiliaryPriority("3"); + configTermTextList.add(configTermText); @@ -543,33 +537,36 @@ public class PlotConstructor2 extends ElementConstructor { * 4. 无论哪种情况都会跳下一步剧情 */ - configTerm = new ConfigTerm( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", + "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("queryskip1",false); - configTerm.setjStatus(1); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("queryskip1",false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); - configTerm = new ConfigTerm( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", + "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("queryskip2",false); - configTerm.setjStatus(1); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); - - configTerm = new ConfigTerm( - " ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" + configTermText.setStatus("sleeping"); + configTermText.setConfigName("queryskip2",false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); + + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=not_found", "match", + "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("queryskip3",false); - configTerm.setjStatus(1); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("queryskip3",false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); @@ -580,66 +577,70 @@ public class PlotConstructor2 extends ElementConstructor { */ //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 - configTerm = new ConfigTerm(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); - configTerm.setNextStepStatus("active"); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); + configTermText = new ConfigTermText(" ", " ", "activate,post::gameQA(" + QA_URL + ")", + "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); + configTermText.setNextStepStatus("active"); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); - configTerm = new ConfigTerm( - " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=not_found", "match,return-0", + "{unknownText-2}", " ", "" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("unknown1",false); - configTerm.setjStatus(1); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("unknown1",false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); - configTerm = new ConfigTerm( + configTermText = new ConfigTermText( " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", + UNKNOWN_TEXT, " ", "" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("unknown2",false); - configTerm.setjStatus(1); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("unknown2",false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + 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", - "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", + UNKNOWN_TEXT, " ", "" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("unknown3",false); - configTerm.setjStatus(1); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("unknown3",false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); - configTerm = new ConfigTerm( - " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", + "{unknownText-2}", " ", "" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("unknown4",false); - configTerm.setjStatus(1); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("unknown4",false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 - configTerm = new ConfigTerm( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "" ," ", "" + configTermText = new ConfigTermText( + " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", + "" ," ", "" ); - configTerm.setStatus("sleeping"); - configTerm.setConfigName("common_answer",false); - configTerm.setjStatus(1); - configTerm.setAuxiliaryPriority("0"); - configTermList.add(configTerm); + configTermText.setStatus("sleeping"); + configTermText.setConfigName("common_answer",false); + configTermText.setjStatus(1); + configTermText.setAuxiliaryPriority("0"); + configTermTextList.add(configTermText); //--------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------- @@ -648,16 +649,24 @@ public class PlotConstructor2 extends ElementConstructor { * ---------------------------------------------------------------------------------------------------- * 用于存档 */ - configTerm = new ConfigTerm( - "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", "" + configTermText = new ConfigTermText( + "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", + "{archiveOperation-2}" ," ", "" ); - configTerm.setAuxiliaryPriority("4"); - configTermList.add(configTerm); + configTermText.setAuxiliaryPriority("4"); + configTermTextList.add(configTermText); } + /** + * 新建一个剧情结点 + * @param node + * @param id + * @param nextId + * @param nextUnknownText + */ public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ String condition = (String) node.get("conditionName"); @@ -684,6 +693,12 @@ public class PlotConstructor2 extends ElementConstructor { } + + /** + * 从配置文件中获取游戏开始时 游戏选择 的剧情, 即选择开始或者重新开始或者根据不同地点读档 + * @param gameElements + * @param keywordMap + */ void addGameStartPlot(JSONObject gameElements, Map keywordMap){ @@ -709,7 +724,7 @@ public class PlotConstructor2 extends ElementConstructor { gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); gameElements.put("start", "start1"); - gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); + gameElements.put("firstUnknownText", GAME_START_HINT); br.close(); @@ -725,22 +740,31 @@ public class PlotConstructor2 extends ElementConstructor { //如果是无条件剧情,那么需要跟着一个激活操作 - public void unconditionalPlotProcess(ConfigTerm configTerm, String nextCondition, Boolean activateFlag){ - configTerm.setFeature(configTerm.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")"); + public void unconditionalPlotProcess(ConfigTermText configTermText, String nextCondition, Boolean activateFlag){ + configTermText.setFeature(configTermText.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); // //if() if(activateFlag){ - configTerm.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*"); + configTermText.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*"); }else { - configTerm.setNextStep("queryskip*,map*,item*,npc*"); + configTermText.setNextStep("queryskip*,map*,item*,npc*"); } - //将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中 - configTerm.setUpdateKnowledge(configTerm.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); - configTerm.setNextStepStatus("active"); + //将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中,激活查询配置后,最后返回的condition应该是剧情指定的下一个condition + configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); + configTermText.setNextStepStatus("active"); } + + /** + * 在条件文本后面添加一个条件 + * @param premiseStr + * @param conditionName + * @param cmpType + * @param operator + * @param value + */ public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ int strLen = premiseStr.length(); String split_punt = ""; @@ -772,6 +796,13 @@ public class PlotConstructor2 extends ElementConstructor { featureStr.append(key); } + + /** + * 除了激活下一步剧情外,还可以同时激活其他地点的剧情,可以在剧情一开始就把ABC三个地点的剧情都激活,这样就不需要先玩完A,才能玩B + * @param updateKnowledge + * @param nextPlotLocation + * @param activateExtraPlot 激活id列表 + */ public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){ JSONObject plot = null; String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = ""; @@ -787,7 +818,7 @@ public class PlotConstructor2 extends ElementConstructor { conditionName = plot.getString("conditionName"); if(conditionName == null || conditionName.equals("")){ - conditionName = "yaobuyao"; + conditionName = DEFAULT_CONDITION; } location = plot.getString("place"); @@ -800,7 +831,6 @@ public class PlotConstructor2 extends ElementConstructor { appendKnowledge(newUK, lastTaskReply, plotText); appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId)); 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 { adjNode.put("prevAutoJump", thisAutoJump); queue.add(adjNode); } else { - conditionDescription.put(adjId, "剧情" + adjId + "进度"); + conditionDescription.put(adjId, String.format(PLOT_STATUS, adjId)); varInitialMap.put(adjId, ""); } } @@ -829,18 +859,6 @@ public class PlotConstructor2 extends ElementConstructor { */ 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(); JSONArray curPremiseList = new JSONArray(); //curPremiseList.add(curPremise.toString()); @@ -848,10 +866,14 @@ public class PlotConstructor2 extends ElementConstructor { JSONArray hisPremiseList = new JSONArray(); //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_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")); diff --git a/src/processing/ActionMatcher.java b/src/processing/ActionMatcher.java index f22c480..bcd031f 100644 --- a/src/processing/ActionMatcher.java +++ b/src/processing/ActionMatcher.java @@ -24,8 +24,6 @@ public class ActionMatcher { static String API_ERROR = "api处理过程中出错了"; - - public LogWriter logWriter = null; public UserInfo userinfo = null; public ServletContext context = null; @@ -35,15 +33,18 @@ public class ActionMatcher { public WorldController worldController = null; BasicBotUtil botUtil = null; - public ActionMatcher(Map curInfoPoint, Map historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv, BasicBotUtil botUtil) { + public ActionMatcher(Map curInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, BasicBotUtil botUtil) { this.curInfoPoint = curInfoPoint; - this.historyInfoPoint = historyInfoPoint; + this.historyInfoPoint = botUtil.getChatCache().getInfoPoint(); this.logWriter = logWriter; this.userinfo = userinfo; this.context = context; - this.gameEnv = gameEnv; + this.worldController = new WorldController(logWriter, userinfo); this.botUtil = botUtil; + if(botUtil.botType.equals("game")) { + this.gameEnv = botUtil.getChatCache().getGameEnv(); + } } @@ -53,7 +54,6 @@ public class ActionMatcher { - /** * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch * @@ -235,7 +235,7 @@ public class ActionMatcher { //没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过 if(!activateFlag && !replaceFlag && !parentFlag) { logWriter.record("-----------------------------------优先级不足,跳过", 0); - logWriter.record(userinfo.id2config.get(action.getId()), 1); + //logWriter.record(userinfo.id2config.get(action.getId()), 1); continue; } @@ -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; @@ -887,7 +860,8 @@ public class ActionMatcher { }else if(postType.equals("term")){ poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansAction, url); }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; diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index 6345d8c..56e83b2 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -30,7 +30,7 @@ public class ChatCacheController { private static String ENV_POSTFIX = "-env.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 = "@@@@"; @@ -41,7 +41,7 @@ public class ChatCacheController { * * @return 历史信息点,对话过程中引擎提取的用户信息 */ - public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map receiveParamters, Boolean loadCacheStatus) throws Exception { + public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, String botType) throws Exception { Map chatCacheMap = null; ChatCache chatCache = null; @@ -60,7 +60,7 @@ public class ChatCacheController { //如果用户之前没有玩过或者有一段时间没有玩 if(chatCache == null){ - chatCache = new ChatCache(userinfo, userKey, randKey); + chatCache = new ChatCache(userinfo, userKey, randKey, botType); chatCacheMap.put(userKey, chatCache); //用户几分钟前还在玩 } else { @@ -69,7 +69,7 @@ public class ChatCacheController { if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) { ChatCacheController.saveChatCache(chatCache, null); } - chatCache = new ChatCache(userinfo, userKey, randKey); + chatCache = new ChatCache(userinfo, userKey, randKey, botType); chatCacheMap.put(userKey, chatCache); } } @@ -79,9 +79,10 @@ public class ChatCacheController { e.printStackTrace(); //chatCache = new ChatCache(userinfo, userKey, randKey); - chatCacheMap.put(userKey, chatCache); + //chatCacheMap.put(userKey, chatCache); } + System.out.println(chatCache.getGameEnv()); return chatCache; } @@ -235,12 +236,13 @@ public class ChatCacheController { /** * 根据chatKey更新chatCache的数据,并修改最后更新时间 */ - public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { - historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); + public static synchronized void updateChatCache4Insert(Map curInfoPoint, ChatCache chatCache, ServletContext context, UserInfo userInfo) { + chatCache.getInfoPoint().put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); Map keyCacheMap = (Map) context.getAttribute("chatCache"); - ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); - chatCache.setInfoPoint(historyInfoPoint); - chatCache.setGameEnv(gameEnv); + keyCacheMap.put(chatCache.getUserKey(), chatCache); + //ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); + //chatCache.setInfoPoint(historyInfoPoint); + //chatCache.setGameEnv(gameEnv); context.setAttribute("chatCache", keyCacheMap); } diff --git a/src/processing/ConditionTableController.java b/src/processing/ConditionTableController.java deleted file mode 100644 index 730fcc0..0000000 --- a/src/processing/ConditionTableController.java +++ /dev/null @@ -1,239 +0,0 @@ -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 conditionList = userInfo.conditionTable.get(conditionName); - Iterator 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 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 conditionList = userInfo.conditionTable.get(conditionName); - Iterator 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 conditionList = new ArrayList(); - 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 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 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; - } -} diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java index 28daa2e..21b52be 100644 --- a/src/processing/FormsPoster.java +++ b/src/processing/FormsPoster.java @@ -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"))){ 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"); } diff --git a/src/processing/SimpleUtil.java b/src/processing/SimpleUtil.java index 747dd12..1d9ecfa 100644 --- a/src/processing/SimpleUtil.java +++ b/src/processing/SimpleUtil.java @@ -134,12 +134,12 @@ public class SimpleUtil { try { HttpResponse resp = client.execute(httpPost); + jobj.put("status_code", resp.getStatusLine().getStatusCode()); if (resp.getStatusLine().getStatusCode() == 200) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "UTF-8"); jobj = JSONObject.parseObject(respContent); jobj.put("post_status", 1); - } else { jobj.put("post_status", 0); jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase()); diff --git a/src/processing/UserInfoController.java b/src/processing/UserInfoController.java index 0538156..7f58522 100644 --- a/src/processing/UserInfoController.java +++ b/src/processing/UserInfoController.java @@ -8,12 +8,15 @@ import java.io.*; import java.sql.SQLException; import java.util.*; +import static com.qiwu.chatbotbackend.Config.Config.TEXT_PARSE_ERROR; + public class UserInfoController { static String CONFIG_DIR = System.getProperty("user.dir") + "/config"; static String FILE_ERROR = ".txt文件有误"; + /** * 根据本地配置文件生成用户信息 */ @@ -82,6 +85,12 @@ public class UserInfoController { } + /** + * 解析一行配置文件 + * @param action + * @param line + * @return + */ public static Action buildCondition(Action action, String line) { String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[]; @@ -90,8 +99,6 @@ public class UserInfoController { 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]; if(text.length > 1 && text[1].startsWith("<-")) line += "---" + text[1]; @@ -102,10 +109,14 @@ public class UserInfoController { cur_premises = premises[0].split(","); history_premises = premises[1].split(","); - if (premises.length < 4) - action.setAuxiliaryPriority(0); - else - action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1])); + + action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1])); + //action.setConfigName(premises[4].split("=", 2)[1]); + + + next = element[1].split("\\|"); + if (next.length < 4) + return action; if(premises.length < 5) action.setConfigName(""); @@ -113,11 +124,9 @@ public class UserInfoController { action.setConfigName(premises[4].split("=", 2)[1]); - next = element[1].split("\\|"); - if (next.length < 4) - return action; + + //回答可以有多个,然后可随机选择一个 action.setAnswer(next[0].split("~")); - //action.nextStep = next[1]; //第二处 action.setNextStep(next[1].split("=", 2)[1]); action.setId(Integer.parseInt(next[3].split("=")[1])); @@ -171,7 +180,7 @@ public class UserInfoController { } catch (IndexOutOfBoundsException e) { e.printStackTrace(); System.out.println(line); - System.out.println("文本格式有误"); + System.out.println(TEXT_PARSE_ERROR); } return action; } @@ -235,7 +244,7 @@ public class UserInfoController { } } catch (ArrayIndexOutOfBoundsException e) { - System.out.println("数据格式有误"); + System.out.println(TEXT_PARSE_ERROR); e.printStackTrace(); } catch (Exception e) { diff --git a/src/processing/WorldController.java b/src/processing/WorldController.java index 4c1f6b5..31ab377 100644 --- a/src/processing/WorldController.java +++ b/src/processing/WorldController.java @@ -3,7 +3,6 @@ package com.qiwu.chatbotbackend.processing; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2; import com.qiwu.chatbotbackend.task.utils.GameBotUtil; import java.util.ArrayList; @@ -11,6 +10,8 @@ import java.util.List; import java.util.Map; import java.util.regex.Matcher; +import static com.qiwu.chatbotbackend.Config.Config.*; + public class WorldController { public LogWriter logWriter = null; public UserInfo userInfo = null; @@ -41,7 +42,7 @@ public class WorldController { subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); returnStr = gameEnv.queryGoodsIntroByGoodsName(subValuePair[1]); if(returnStr == null ) - returnStr = "无"; + returnStr = DONT_FOUND; break; case "queryAttrByGoodsName": @@ -49,16 +50,16 @@ public class WorldController { value = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]); if(returnStr == null) { - returnStr = "没找到"; + returnStr = DONT_FOUND; }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; case "queryAllAttrByGoodsName": textList = gameEnv.queryGoodsAllAttrByGoodsName(varName); if(textList == null || textList.size() == 0) - returnStr = "无"; + returnStr = DONT_FOUND; else { for (String site : textList) returnStr += "、" + site; @@ -68,7 +69,7 @@ public class WorldController { case "queryAroundGoodsByClassName": textList = gameEnv.queryGoodsByClassAndSite(namePair[1], historyInfoPoint.get("site")); if(textList == null || textList.size() == 0) - returnStr = "无"; + returnStr = DONT_FOUND; else { for (String site : textList) returnStr += "、" + site; @@ -82,14 +83,14 @@ public class WorldController { ItemName = gameEnv.getGoodsNameByNickname(currentLocation, ItemName); returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); if(returnStr == null || returnStr.equals("否")){ - returnStr = "隐藏了"; + returnStr = ATTRIBUTE_HIDDEN; } else if(returnStr.equals("是")){ location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); if(location == null){ - returnStr = "没找到"; + returnStr = DONT_FOUND; }else{ - owner = gameEnv.queryGoodsAttrByGoodsName(ItemName, "所属角色"); - logWriter.record(ItemName + "-owner:" + owner, 0); + owner = gameEnv.queryGoodsAttrByGoodsName(ItemName, "owner"); + //logWriter.record(ItemName + "-owner:" + owner, 0); if(owner != null && !owner.equals("")){ //如果物品的所属角色是玩家,那么回答物品在你身上 @@ -97,11 +98,14 @@ public class WorldController { returnStr = userInfo.varInitialMap.get("ITEM_IS_YOURS"); }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 { //没有所属角色就回答物品在某个地点 - 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 { String player = gameEnv.queryPlayerName(); textList = gameEnv.queryGoodsByNpcName(player); if(textList == null || textList.size() == 0) - returnStr = "什么都没有"; + returnStr = NOTHING_FOUND; else { for (String site : textList) 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; @@ -126,13 +130,13 @@ public class WorldController { ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); if(returnStr == null || returnStr.equals("否")){ - returnStr = "没找到"; + returnStr = DONT_FOUND; } else if(returnStr.equals("是")){ location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); if(location == null){ - returnStr = "没找到"; + returnStr = DONT_FOUND; }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 { subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); returnStr = gameEnv.queryNpcIntroByNpcName(subValuePair[1]); if(returnStr == null) - returnStr = "无"; + returnStr = DONT_FOUND; break; case "queryAttrByNPCName": @@ -156,10 +160,10 @@ public class WorldController { subValuePair[0] = subValuePair[0].replace("哪里", "location"); value = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); if(value == null) { - returnStr = "没找到"; + returnStr = DONT_FOUND; }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; @@ -169,7 +173,7 @@ public class WorldController { location = gameEnv.queryNpcAttrByNpcName(valuePair[1], "location"); if(location == null){ - returnStr = "没找到"; + returnStr = DONT_FOUND; }else{ returnStr = location; } @@ -183,15 +187,15 @@ public class WorldController { System.out.println(NPCName); returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); if(returnStr == null || returnStr.equals("否")){ - returnStr = "没找到"; + returnStr = DONT_FOUND; } else if(returnStr.equals("是")){ location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); if(location == null){ - returnStr = "没找到"; + returnStr = DONT_FOUND; }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; @@ -202,13 +206,13 @@ public class WorldController { NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); if(returnStr == null || returnStr.equals("否")){ - returnStr = "没找到"; + returnStr = DONT_FOUND; } else if(returnStr.equals("是")){ location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); if(location == null){ - returnStr = "没找到"; + returnStr = DONT_FOUND; }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 { 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; @@ -236,16 +240,13 @@ public class WorldController { switch (valuePair[0]) { case "queryAroundAllBySite": - if(userInfo.varInitialMap.containsKey("AROUND_THINGS")) { - format = userInfo.varInitialMap.get("AROUND_THINGS"); - }else { - format = "周围有[人物物品列表]"; - } + format = userInfo.varInitialMap.get("AROUND_THINGS"); + sites = gameEnv.queryAroundAllBySite(historyInfoPoint.get("site")); if(sites == null || sites.size() == 0) - returnStr = "什么都没有"; + returnStr = NOTHING_FOUND; else { StringBuffer text = new StringBuffer(); @@ -254,20 +255,16 @@ public class WorldController { text.append("、" + site); } - returnStr = format.replace("[人物物品列表]", text.substring(1)); + returnStr = format.replace(NPC_ITEM_LIST_SLOT, text.substring(1)); } break; case "queryAroundNpcBySite": - if(userInfo.varInitialMap.containsKey("AROUND_PEOPLE")) { - format = userInfo.varInitialMap.get("AROUND_PEOPLE"); - }else { - format = "周围有[人物列表]"; - } + format = userInfo.varInitialMap.get("AROUND_PEOPLE"); sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); if(sites == null || sites.size() == 0) - returnStr = "什么都没有"; + returnStr = NOTHING_FOUND; else { StringBuffer text = new StringBuffer(); @@ -276,20 +273,16 @@ public class WorldController { text.append("、" + site); } - returnStr = format.replace("[人物列表]", text.substring(1)); + returnStr = format.replace(NPC_LIST_SLOT, text.substring(1)); } break; case "queryAroundGoodsBySite": - if(userInfo.varInitialMap.containsKey("AROUND_ITEMS")) { - format = userInfo.varInitialMap.get("AROUND_ITEMS"); - }else { - format = "周围有[物品列表]"; - } + format = userInfo.varInitialMap.get("AROUND_ITEMS"); sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site")); if(sites == null || sites.size() == 0) - returnStr = "什么都没有"; + returnStr = NOTHING_FOUND; else { if(sites.size() > 0) { StringBuffer text = new StringBuffer(); @@ -297,17 +290,13 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = format.replace("[物品列表]", text.substring(1)); + returnStr = format.replace(ITEM_LIST_SLOT, text.substring(1)); } } break; case "queryCanGoBySite": - if(userInfo.varInitialMap.containsKey("CAN_GO_SITES")) { - format = userInfo.varInitialMap.get("CAN_GO_SITES"); - }else { - format = "你可以去[可去列表]"; - } + format = userInfo.varInitialMap.get("CAN_GO_SITES"); sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); if(sites == null) { @@ -322,17 +311,13 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = format.replace("[可去列表]", text.substring(1)); + returnStr = format.replace(CAN_GO_SITE_SLOT, text.substring(1)); } } break; case "queryHowToPathBySite": - if(userInfo.varInitialMap.containsKey("PATH_EXIST")) { - format = userInfo.varInitialMap.get("PATH_EXIST"); - }else { - format = "通过[途径]可以到达[目的地]"; - } + format = userInfo.varInitialMap.get("PATH_EXIST"); if(!currentInfoPoint.containsKey(valuePair[1])) { returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST"); @@ -352,17 +337,14 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", destination); + returnStr = format.replace(PATH_SLOT, text.substring(1)).replace(DESTINATION_SLOT, destination); } } break; case "queryToDoPathBySite": - if(userInfo.varInitialMap.containsKey("SITE_NOT_ADJOINT")) { - format = userInfo.varInitialMap.get("SITE_NOT_ADJOINT"); - }else { - format = "通过[途径]可以到达[目的地]"; - } + format = userInfo.varInitialMap.get("SITE_NOT_ADJOINT"); + destination = currentInfoPoint.get(valuePair[1]).split(":")[1]; destination = gameEnv.getPlaceNameByNickname(start, destination); @@ -381,7 +363,7 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", destination); + returnStr = format.replace(PATH_SLOT, text.substring(1)).replace(DESTINATION_SLOT, destination); } } break; @@ -390,16 +372,13 @@ public class WorldController { returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; break; case "queryAroundPlace": - if(userInfo.varInitialMap.containsKey("AROUND_PLACE")) { - format = userInfo.varInitialMap.get("AROUND_PLACE"); - }else { - format = "周围有[地点列表]"; - } + + format = userInfo.varInitialMap.get("AROUND_PLACE"); sites = gameEnv.queryCanGoBySite(start); if(sites == null || sites.size() == 0) { - returnStr = "无处可去了"; + returnStr = NOWHERE_CAN_GO; } else { if(sites.size() > 0) { StringBuffer text = new StringBuffer(); @@ -407,21 +386,17 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = format.replace("[地点列表]", text.substring(1)); + returnStr = format.replace(SITE_LIST_SLOT, text.substring(1)); } } break; case "queryInnerNpcBySite": - if(userInfo.varInitialMap.containsKey("INNER_PEOPLE")) { - format = userInfo.varInitialMap.get("INNER_PEOPLE"); - }else { - format = "里面有[人物列表]"; - } + format = userInfo.varInitialMap.get("INNER_PEOPLE"); sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); if(sites == null || sites.size() == 0) - returnStr = "什么都没有"; + returnStr = NOTHING_FOUND; else { StringBuffer text = new StringBuffer(); @@ -430,30 +405,33 @@ public class WorldController { text.append("、" + site); } - returnStr = format.replace("[人物列表]", text.substring(1)); + returnStr = format.replace(NPC_LIST_SLOT, text.substring(1)); } break; case "queryTaskDescription": - if(userInfo.varInitialMap.containsKey("TASK_DESCRIPTION")) { - format = userInfo.varInitialMap.get("TASK_DESCRIPTION"); - }else { - format = "我们的任务是[任务描述]"; - } + format = userInfo.varInitialMap.get("TASK_DESCRIPTION"); - returnStr = format.replace("[任务描述]", userInfo.varInitialMap.get(PlotConstructor2.TASK_DESCRIPTION)); + returnStr = format.replace(TASK_DESCRIPTION_SLOT, userInfo.varInitialMap.get(TASK_DESCRIPTION)); break; 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; 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; case "queryPathAdjoin": returnStr = userInfo.varInitialMap.get("PATH_ADJOINT"); break; + case "queryItemsInPlace": + break; + case "queryNPCInPlace": + break; + case "queryThingsInPlace": + break; + } } diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index cfe4ae5..af68997 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet; import com.alibaba.fastjson.JSONObject; 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.gameDesign.*; import com.qiwu.chatbotbackend.processing.ChatCacheController; @@ -21,6 +21,8 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; +import static com.qiwu.chatbotbackend.Config.Config.CONDITION_GENERATE_URL; + @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) public class GameDesignServlet extends HttpServlet { @@ -166,8 +168,8 @@ public class GameDesignServlet extends HttpServlet { helper.batchInsertVariableByBotId(botId, constructor); List jsonList = new ArrayList(); - for(ConfigTerm configTerm : constructor.getConfigTermList()){ - json = configTerm.toJson(constructor.getConditionDescription()); + for(ConfigTermText configTermText : constructor.getConfigTermTextList()){ + json = configTermText.toJson(constructor.getConditionDescription()); constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); jsonList.add(json); } @@ -296,7 +298,7 @@ public class GameDesignServlet extends HttpServlet { userInfo.extraInfo.put("activeAction", startCondition); 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) { e.printStackTrace(); } @@ -316,7 +318,7 @@ public class GameDesignServlet extends HttpServlet { public void readKeywords(Map keywordsMap, String path){ File file = new File(path); - String line, pair[]; + String line, elem[]; if(file.exists()){ FileReader reader = null; @@ -326,10 +328,23 @@ public class GameDesignServlet extends HttpServlet { while ((line = br.readLine()) != null) { - if(!line.equals("") && !line.startsWith("#")){ - pair = line.split("\\|", 2); - keywordsMap.put(pair[0], new StringBuffer(pair[1])); + if(!line.equals("") && !line.startsWith("#")) { + elem = line.split("\\|", 3); + + //查看意图是否已经存在相关的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) { e.printStackTrace(); diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index 9c0689c..eb6abcd 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -21,6 +21,9 @@ import java.text.ParseException; import java.util.HashMap; 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"}) public class GetAnswerServlet extends HttpServlet { @@ -36,7 +39,7 @@ public class GetAnswerServlet extends HttpServlet { request.setCharacterEncoding("UTF-8"); Map receiveParamters = new HashMap<>(request.getParameterMap()); Map curInfoPoint = new HashMap(); - Map historyInfoPoint = null; + //Map historyInfoPoint = null; Solution bestMatch = null; BasicBotUtil botUtil = null; Action ansAction = null; @@ -49,7 +52,7 @@ public class GetAnswerServlet extends HttpServlet { //如果有client_id,会用@分隔 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){ userKey = chatKeys[0]; randKey = chatKeys[0]; @@ -83,12 +86,20 @@ public class GetAnswerServlet extends HttpServlet { //获得用户历史信息 ChatCache chatCache = null; Boolean loadCacheStatus = Boolean.valueOf(false); + + if(userinfo.varInitialMap.get("botType") != null) + botType = userinfo.varInitialMap.get("botType"); + + try { - chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus); - } catch (SQLException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); + chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, botType); + + if(chatCache == null){ + throw(new Exception("chatCache初始化失败")); + } + } catch (Exception e) { + System.out.println(e.getMessage()); + //e.printStackTrace(); } /** @@ -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){ case "game": 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; default: - botUtil = new BasicBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter); + botUtil = new BasicBotUtil(curInfoPoint, chatCache, userinfo, logWriter); break; } @@ -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); if (state.equals("") && ansAction.getPriority()== -1) state = "我不理解,"; @@ -129,24 +139,31 @@ public class GetAnswerServlet extends HttpServlet { bestMatch = matcher.getSolution(ansAction, context, userinfo); - //读档成功不应该再激活 - //if(matcher.) - if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) { - //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 - bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); + + if(!botUtil.getChatCache().getReload()) { + //读档成功不应该再激活 + //if(matcher.) + 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) { e.printStackTrace(); } } 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); - historyInfoPoint.put("lastReply", bestMatch.getAnswer()); + botUtil.getChatCache().getInfoPoint().put("lastReply", bestMatch.getAnswer()); if (debugFlag) { matcher.appendDebugInfo(bestMatch, context); } @@ -156,7 +173,7 @@ public class GetAnswerServlet extends HttpServlet { 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) context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); @@ -172,6 +189,8 @@ public class GetAnswerServlet extends HttpServlet { ansJ = "找不到配置文件"; } + System.out.println(TEST_VAR); + logWriter.writeln(); diff --git a/src/task/utils/BasicBotUtil.java b/src/task/utils/BasicBotUtil.java index cadc92c..0578adc 100644 --- a/src/task/utils/BasicBotUtil.java +++ b/src/task/utils/BasicBotUtil.java @@ -1,6 +1,7 @@ package com.qiwu.chatbotbackend.task.utils; import com.qiwu.chatbotbackend.entity.Action; +import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.processing.LogWriter; @@ -15,19 +16,23 @@ import java.util.regex.Pattern; public class BasicBotUtil { Map curInfoPoint = null; - Map historyInfoPoint = null; UserInfo userinfo = null; LogWriter logWriter = null; + ChatCache chatCache = null; + public String botType = "basic"; + public ChatCache getChatCache() { + return chatCache; + } public BasicBotUtil(){}; - public BasicBotUtil(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, LogWriter logWriter){ + public BasicBotUtil(Map curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter){ this.curInfoPoint = curInfoPoint; - this.historyInfoPoint = historyInfoPoint; this.userinfo = userinfo; this.logWriter = logWriter; + this.chatCache = chatCache; } public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { @@ -36,7 +41,6 @@ public class BasicBotUtil { } - //在接收到请求后对数据做处理,转化为系统可以处理的数据 /** @@ -104,18 +108,18 @@ public class BasicBotUtil { } String currentAction = ""; - if (historyInfoPoint.containsKey("currentAction")) - currentAction = historyInfoPoint.get("currentAction"); + if (chatCache.getInfoPoint().containsKey("currentAction")) + currentAction = chatCache.getInfoPoint().get("currentAction"); else if (userinfo.extraInfo.containsKey("activeAction")) { currentAction = userinfo.extraInfo.get("activeAction"); - historyInfoPoint.put("currentAction", currentAction); + chatCache.getInfoPoint().put("currentAction", currentAction); } else currentAction = " "; curInfoPoint.put("emptySet", " "); - if (historyInfoPoint.get("activeList") == null) { - historyInfoPoint.put("activeList", currentAction); + if (chatCache.getInfoPoint().get("activeList") == null) { + chatCache.getInfoPoint().put("activeList", currentAction); } if (unknown_flag && !currentAction.equals("")) { @@ -123,7 +127,7 @@ public class BasicBotUtil { curInfoPoint.put(currentAction, i); } - logWriter.record("historyInfoPoint:" + historyInfoPoint.toString(), 1); + logWriter.record("historyInfoPoint:" + chatCache.getInfoPoint().toString(), 1); @@ -131,8 +135,8 @@ public class BasicBotUtil { } public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ - if(historyInfoPoint.get("error_message") != null && historyInfoPoint.get("error_message") != ""){ - bestMatch.setAnswer(bestMatch.getAnswer() + historyInfoPoint.get("error_message")); + if(chatCache.getInfoPoint().get("error_message") != null && chatCache.getInfoPoint().get("error_message") != ""){ + bestMatch.setAnswer(bestMatch.getAnswer() + chatCache.getInfoPoint().get("error_message")); } @@ -172,7 +176,7 @@ public class BasicBotUtil { * @param updateValue */ public void putKeyword(String variableName, String updateValue){ - historyInfoPoint.put(variableName, updateValue); + chatCache.getInfoPoint().put(variableName, updateValue); } public String knowledgeProcess(String variableName, String updateValue){ @@ -209,11 +213,11 @@ public class BasicBotUtil { reply = reply.replace("{" + variable + "-1}", keyword); } } else if (m.group(1).endsWith("-2}")) { - if (historyInfoPoint.get(variable) != null) - if(historyInfoPoint.get(variable).equals("do_reset")){ + if (chatCache.getInfoPoint().get(variable) != null) + if(chatCache.getInfoPoint().get(variable).equals("do_reset")){ reply = reply.replace("{" + variable + "-2}", ""); }else - reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); + reply = reply.replace("{" + variable + "-2}", chatCache.getInfoPoint().get(variable)); } } diff --git a/src/task/utils/ContextDestroyListener.java b/src/task/utils/ContextDestroyListener.java new file mode 100644 index 0000000..5471da6 --- /dev/null +++ b/src/task/utils/ContextDestroyListener.java @@ -0,0 +1,58 @@ +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 chatCacheMap = (Map)obj; + + Iterator 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(); + } + } + } + +} diff --git a/src/task/utils/ContextInitialListener.java b/src/task/utils/ContextInitialListener.java new file mode 100644 index 0000000..f4f93c5 --- /dev/null +++ b/src/task/utils/ContextInitialListener.java @@ -0,0 +1,30 @@ +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(); + + + + + + + } + +} diff --git a/src/task/utils/DataDeliver.java b/src/task/utils/DataDeliver.java index 6d3cbea..91bfd1e 100644 --- a/src/task/utils/DataDeliver.java +++ b/src/task/utils/DataDeliver.java @@ -5,18 +5,17 @@ import com.qiwu.chatbotbackend.processing.SimpleUtil; import java.io.UnsupportedEncodingException; +import static com.qiwu.chatbotbackend.Config.Config.CC_URL; + public class DataDeliver extends Thread { JSONObject data = null; - String url = ""; + String url = CC_URL; public void setData(JSONObject data) { this.data = data; } - public void setUrl(String url) { - this.url = url; - } @@ -25,7 +24,7 @@ public class DataDeliver extends Thread { System.out.println("线程开始"); System.out.println(url); try { - SimpleUtil.postJSON(url, data, null); + SimpleUtil.postJSON(CC_URL, data, null); System.out.println("线程完成"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); diff --git a/src/task/utils/FileFinder.java b/src/task/utils/FileFinder.java index 1097ca3..db2c1ef 100644 --- a/src/task/utils/FileFinder.java +++ b/src/task/utils/FileFinder.java @@ -7,6 +7,8 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static com.qiwu.chatbotbackend.processing.ChatCacheController.COMBINE_PUNC1; + /** * 实现一个支持通配符的基于广度优先算法的文件查找器 */ @@ -88,7 +90,7 @@ public class FileFinder { public static boolean deleteGameArchive(String baseDirName, String botAccount){ String tempName; - String regEx = ".*@@@" + botAccount + "@@@@.*"; + String regEx = ".*" + COMBINE_PUNC1 + botAccount + "-.*"; List fileList = new ArrayList(); Pattern pattern = Pattern.compile(regEx); Matcher matcher = null; diff --git a/src/task/utils/GameBotUtil.java b/src/task/utils/GameBotUtil.java index ba76fa0..7cdcbb1 100644 --- a/src/task/utils/GameBotUtil.java +++ b/src/task/utils/GameBotUtil.java @@ -4,7 +4,6 @@ import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.*; -import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2; import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.SimpleUtil; @@ -17,32 +16,30 @@ import java.util.*; import java.util.regex.Matcher; 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; public class GameBotUtil extends BasicBotUtil{ 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_LAST = "load_last"; - public GameBotUtil(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, LogWriter logWriter, WorldController worldController, GameEnv gameEnv, ChatCache chatCache){ - this.curInfoPoint = curInfoPoint; - this.historyInfoPoint = historyInfoPoint; - this.userinfo = userinfo; - this.logWriter = logWriter; - this.gameEnv = gameEnv; - this.chatCache = chatCache; + + + public GameBotUtil(Map curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter, WorldController worldController){ + super(curInfoPoint, chatCache, userinfo, logWriter); this.worldController = worldController; + this.botType = "game"; } + + @Override public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { - Boolean debugFlag = infoPointPreprocessing(receiveParameters, context, false); + Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false); //将要去的地点的别名替换为真名 // String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; @@ -66,11 +63,11 @@ public class GameBotUtil extends BasicBotUtil{ // 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){ - historyInfoPoint.put("临时变量condition", "yaobuyao"); + chatCache.getInfoPoint().put("临时变量condition", "yaobuyao"); }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{ StringBuffer finalText = new StringBuffer(); - String plotText = bestMatch.getAnswer(); + String plotText = SimpleUtil.randStr(bestMatch.getAnswer().split("~")); //将自动跳转文本、qa文本、查询文本拼接 String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text", "error_message"}; String queryResult; Set keepNoSpeaker = new HashSet(){ { add("sendData:archiveList"); - add("请说开始剧情或者继续剧情"); + add(GAME_START_HINT); } }; - historyInfoPoint.put("plot_text", plotText); + chatCache.getInfoPoint().put("plot_text", plotText); //整合qa问答、地图、npc查询文本和剧情文本 for(String queryName:queryList){ - queryResult = historyInfoPoint.get(queryName); + queryResult = chatCache.getInfoPoint().get(queryName); if(queryResult != null){ if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本 //剧情可以为空,其他不行 @@ -116,7 +113,7 @@ public class GameBotUtil extends BasicBotUtil{ case "goods_query": case "npc_query": 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); break; case "plot_text": @@ -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{ String keyword = ""; String nameSeries[] = actionName.split("_"); + //变量名以npc_开头,就从游戏环境中查询相应的值 if(actionName.startsWith("npc_")){ if(nameSeries.length == 4){ - keyword = gameEnv.queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]); + keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]); }else if (nameSeries.length == 3){ if(nameSeries[1].equals("玩家") && nameSeries[2].equals("物品栏")) { StringBuffer sb = new StringBuffer(); - List goods = gameEnv.queryGoodsByNpcName("玩家"); + List goods = chatCache.getGameEnv().queryGoodsByNpcName("玩家"); for (String good : goods) { sb.append("+").append(good); } keyword = sb.toString(); }else{ - keyword = gameEnv.queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]); + keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]); } } }else if (actionName.startsWith("goods_")) { - nameSeries[2] = nameSeries[2].replace("所属角色", "owner"); - keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); + if(nameSeries.length == 3) { + nameSeries[2] = nameSeries[2].replace("所属角色", "owner"); + keyword = chatCache.getGameEnv().queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); + } //System.out.println("return" + keyword); @@ -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("")){ keyword = "not_exist"; }else { - logWriter.record("isNeighbour(" + historyInfoPoint.get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1); - keyword = String.valueOf(gameEnv.isNeighbour(historyInfoPoint.get("site"), curInfoPoint.get(opPair[1]).split(":")[1])); + logWriter.record("isNeighbour(" + chatCache.getInfoPoint().get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1); + keyword = String.valueOf(chatCache.getGameEnv().isNeighbour(chatCache.getInfoPoint().get("site"), curInfoPoint.get(opPair[1]).split(":")[1])); logWriter.record("返回:" + keyword, 1); } }else { @@ -217,15 +217,15 @@ public class GameBotUtil extends BasicBotUtil{ updateValue = "update:" + updateValue; } 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; } catch (Exception e) { 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{ }else if (ansAction.getFeatureMap().containsKey("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); 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 - 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")) { @@ -306,7 +306,6 @@ public class GameBotUtil extends BasicBotUtil{ System.out.println("sendArchiveList"); DataDeliver dataDeliver = new DataDeliver(); - dataDeliver.setUrl(userinfo.varInitialMap.get("CC_URL")); JSONObject data = new JSONObject(); List archiveList = helper.queryArchiveByUserKey(userKey); data.put("data", JSONObject.toJSON(archiveList)); @@ -334,11 +333,15 @@ public class GameBotUtil extends BasicBotUtil{ ChatCache loadCache = null; - //如果存在读档,就要将自动跳转和qa的临时数据清空 - historyInfoPoint.put("plot_jump_text", ""); - historyInfoPoint.put("common_answer", ""); + if (archiveInfo != null) { + + //如果存在读档,就要将自动跳转和qa的临时数据清空 + chatCache.getInfoPoint().put("plot_jump_text", ""); + chatCache.getInfoPoint().put("common_answer", ""); + + try { loadCache = ChatCacheController.loadChatCache(archiveInfo); } catch (Exception e) { @@ -346,6 +349,8 @@ public class GameBotUtil extends BasicBotUtil{ solution.setAnswer("从本地加载存档失败"); e.printStackTrace(); } + + //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); this.chatCache.setInfoPoint(loadCache.getInfoPoint()); this.chatCache.setGameEnv(loadCache.getGameEnv()); @@ -354,8 +359,8 @@ public class GameBotUtil extends BasicBotUtil{ System.out.println("----------读档中------------"); site = loadCache.getInfoPoint().get("site"); - String nextStep = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_CONDITION, site)); - String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_REPLY, site)); + String nextStep = loadCache.getInfoPoint().get(String.format(TASK_CONDITION, site)); + String reply = loadCache.getInfoPoint().get(String.format(TASK_REPLY, site)); solution.setAnswer(reply); solution.setNext("nextStep=" + nextStep); this.chatCache.setReload(true); @@ -383,14 +388,14 @@ public class GameBotUtil extends BasicBotUtil{ switch (varElements[0]){ //如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。 case "globalVariable": - reply = reply.replace(variableSlot, historyInfoPoint.get(variable)); + reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); case "npc": - result = gameEnv.queryNpcAttrByNpcName(varElements[1], varElements[2]); + result = chatCache.getGameEnv().queryNpcAttrByNpcName(varElements[1], varElements[2]); reply = reply.replace(variableSlot, result); case "goods": - result = gameEnv.queryGoodsAttrByGoodsName(varElements[1], varElements[2]); + result = chatCache.getGameEnv().queryGoodsAttrByGoodsName(varElements[1], varElements[2]); reply = reply.replace(variableSlot, result); case "map": @@ -399,8 +404,8 @@ public class GameBotUtil extends BasicBotUtil{ default: if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){ reply = reply.replace(variableSlot, curInfoPoint.get(variable)); - }else if(historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")){ - reply = reply.replace(variableSlot, historyInfoPoint.get(variable)); + }else if(chatCache.getInfoPoint().get(variable) != null && !chatCache.getInfoPoint().get(variable).equals("")){ + reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); } } @@ -451,7 +456,9 @@ public class GameBotUtil extends BasicBotUtil{ int flag = 1; if(m.find()) { npc = m.group(1); + location = gameEnv.queryNpcAttrByNpcName(npc, "location"); + System.out.println("location:" + location + ", npc:" + npc); if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ flag = 1; @@ -488,17 +495,17 @@ public class GameBotUtil extends BasicBotUtil{ String location; Boolean flag = false; - location = gameEnv.queryNpcAttrByNpcName(npc, "location"); + location = chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "location"); if( location == null){ return false; } 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(isOnlineMode(npc, historyInfoPoint)){ + if(isOnlineMode(npc, chatCache.getInfoPoint())){ logWriter.record("\"" + npc + "\":匹配", 1); flag = true; } @@ -519,14 +526,14 @@ public class GameBotUtil extends BasicBotUtil{ public static String appendTalker(String npc, String text, Map 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 textType, returnText = "plot text filt error", plotLastTalker; - String site = historyInfoPoint.get("site"); + String site = chatCache.getInfoPoint().get("site"); textType = textTypeDetect(reply, site); @@ -537,13 +544,13 @@ public class GameBotUtil extends BasicBotUtil{ returnText = reply; break; 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": Set candidates = new HashSet(); Map> npcTextMap = null; String unknownList = "", foundNPC; String fieldList[] = {"unknownTextList", "finalUnknownText"}; - String lastReply = historyInfoPoint.get("lastReply"); + String lastReply = chatCache.getInfoPoint().get("lastReply"); plotLastTalker = findTextLastTalker(lastReply, site); @@ -639,8 +646,8 @@ public class GameBotUtil extends BasicBotUtil{ * includeSiteNPC 是否包含当前地点的npc */ private List findRelateTalkers(Boolean includeSiteNPC){ - String site = historyInfoPoint.get("site"); - String lastReply = historyInfoPoint.get("lastReply"); + String site = chatCache.getInfoPoint().get("site"); + String lastReply = chatCache.getInfoPoint().get("lastReply"); List talkers = new ArrayList(); @@ -653,7 +660,7 @@ public class GameBotUtil extends BasicBotUtil{ } if(includeSiteNPC){ - List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); + List npcList = chatCache.getGameEnv().queryAroundNpcBySite(chatCache.getInfoPoint().get("site")); for(String npc:npcList){ if(canTalk(npc, site, true)){ talkers.add(npc); @@ -662,7 +669,7 @@ public class GameBotUtil extends BasicBotUtil{ } if(talkers.size() == 0){ - talkers.add(historyInfoPoint.get(ASSISTANT)); + talkers.add(chatCache.getInfoPoint().get(ASSISTANT)); } return talkers; -- libgit2 0.27.1