package com.qiwu.chatbotbackend.task.utils; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.SimpleUtil; import com.qiwu.chatbotbackend.processing.WorldController; import javax.servlet.ServletContext; import java.io.IOException; import java.sql.SQLException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.qiwu.chatbotbackend.Config.Config.*; import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; public class GameBotUtil extends BasicBotUtil{ WorldController worldController = null; public static String LOAD_BY_SITE_CONDITION = "load_game_by_site"; public static String LOAD_BY_LAST = "load_last"; public GameBotUtil(Map curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter, WorldController worldController){ super(curInfoPoint, chatCache, userinfo, logWriter); this.worldController = worldController; this.botType = "game"; } /** * 对表单数据做预处理 * @param receiveParameters * @param context * @return * @throws IOException */ @Override public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false); //将要去的地点的别名替换为真名 // String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; // // for(String conditionName: conditionList) { // // if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) { // String info = curInfoPoint.get(conditionName), newInfo = curInfoPoint.get(conditionName); // String destination = info.split(":")[1]; // String site = historyInfoPoint.get("site"); // try { // newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); // }catch(Exception e){ // e.printStackTrace(); // } // // logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); // curInfoPoint.put(conditionName, newInfo); // } // } // historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site")); //将上一轮使用的nextStep(condition)放在临时变量中 String activeList[] = chatCache.getInfoPoint().get("activeList").split("\\|"); if(activeList.length == 0){ chatCache.getInfoPoint().put("临时变量condition", "yaobuyao"); }else { chatCache.getInfoPoint().put("临时变量condition", activeList[activeList.length-1]); } int randomNumber = (int)(Math.random() * 10000); chatCache.getInfoPoint().put(PLOT_RANDOM_NUM, String.valueOf(randomNumber)); return debugFlag; } @Override public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ StringBuffer finalText = new StringBuffer(); String plotText = SimpleUtil.randStr(bestMatch.getAnswer().split("~")); //将自动跳转文本、qa文本、查询文本拼接 String queryList[] = {"common_answer", "plot_jump_text", "map_query", "goods_query", "npc_query", "plot_text", "error_message"}; String queryResult; //有些特殊文本在开头是不加npc名字和情绪的 Set keepNoSpeaker = new HashSet(){ { add("sendData:archiveList"); add(GAME_START_HINT); } }; chatCache.getInfoPoint().put("plot_text", plotText); //整合qa问答、地图、npc查询文本和剧情文本 for(String queryName:queryList){ queryResult = chatCache.getInfoPoint().get(queryName); if(queryResult != null){ if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本 //剧情可以为空,其他不行 continue; } switch (queryName){ case "common_answer": //qa返回结果不为No answer,就添加到回答文本 if(!queryResult.equals("no answer")) finalText.append(queryResult); break; case "plot_jump_text": //添加剧情自动跳转文本 finalText.append(queryResult); break; case "map_query": case "goods_query": case "npc_query": case "error_message": //这四类文本(查询+错误信息)都是动态生成的,没有npc和情绪信息,所以需要添加npc和情绪 queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, chatCache.getInfoPoint(), chatCache.getGameEnv()); finalText.append(queryResult); break; case "plot_text": //有以下剧情文本是 if(keepNoSpeaker.contains(plotText)){ //不需要添加人名和情绪 finalText.setLength(0); finalText.append(plotText); } //文本为空跳过 else if(plotText.equals("") && finalText.length() != 0){ continue; }else { //对剧情文本做处理,或者说对unknown文本做处理 finalText.append(plotTextFilt(plotText)); } break; } chatCache.getInfoPoint().put(queryName, ""); } } bestMatch.setAnswer(finalText.toString()); return true; } @Override public String getKeyword(Map infoPoint, Map infoPoint2, Boolean chooseLater, String actionName){ String keyword = ""; String nameSeries[] = actionName.split("_"); //变量名以npc_开头,就从游戏环境中查询相应的值 if(actionName.startsWith("npc_")){ if(nameSeries.length == 4){ keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]); }else if (nameSeries.length == 3){ if(nameSeries[2].equals("物品栏")) { //如果是物品栏就调用专门的函数查询物品栏的所有数据 StringBuffer sb = new StringBuffer(); List goods = chatCache.getGameEnv().queryGoodsByNpcName(nameSeries[1]); for (String good : goods) { sb.append("+").append(good); } keyword = sb.toString(); }else{ keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]); } } }else if (actionName.startsWith("goods_")) { if(nameSeries.length == 3) { nameSeries[2] = nameSeries[2].replace("所属角色", "owner"); keyword = chatCache.getGameEnv().queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); } //System.out.println("return" + keyword); }else if(actionName.startsWith("isNeighbour")){ String opPair[] = actionName.split(":"); if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){ keyword = "not_exist"; }else { logWriter.record("isNeighbour(" + chatCache.getInfoPoint().get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1); keyword = String.valueOf(chatCache.getGameEnv().isNeighbour(chatCache.getInfoPoint().get("site"), curInfoPoint.get(opPair[1]).split(":")[1])); logWriter.record("返回:" + keyword, 1); } }else { /** * 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字 */ if(chooseLater){ keyword = infoPoint2.get(actionName); if(keyword != null && !keyword.equals("")) return keyword; } keyword = infoPoint.get(actionName); } if(keyword == null) keyword = ""; return keyword; }; @Override public void putKeyword(String variableName, String updateValue){ String namePair[] = variableName.split("_"); //如果变量名开头为NPC或者item,就专门交给游戏环境处理 if ((namePair[0].equals("npc") || namePair[0].equals("goods") || namePair[0].equals("map") || namePair[0].equals("place"))) { try { if (!updateValue.startsWith("query") && !updateValue.startsWith("update")) { updateValue = "update:" + updateValue; } variableName = variableName.replace("所属玩家", "owner"); String returnStr = worldController.worldOperation(chatCache.getGameEnv(), variableName, updateValue, curInfoPoint, chatCache.getInfoPoint()); updateValue = returnStr; } catch (Exception e) { e.printStackTrace(); updateValue = GAME_MODULE_ERROR; } } chatCache.getInfoPoint().put(variableName, updateValue); } public String knowledgeProcess(String variableName, String updateValue){ String values[] = updateValue.split(":",2), returnValue; if(values.length > 1 && values[0].equals("update")) returnValue = values[1]; else returnValue = updateValue; return returnValue; } /** * 主要用于游戏存档和读档 * @param ansAction * @param solution * @throws IOException */ @Override public void extraOperation(Action ansAction, Solution solution) throws IOException { Boolean flag = true; String userKey = curInfoPoint.get("userKey"); String randKey = curInfoPoint.get("randKey"); String keyword = "", site; SqlHelper helper = null; ChatCache chatCache = null; try { helper = new SqlHelper(); //未登录用户没有存取档的操作 if(userKey.equals(randKey)) return; if(ansAction.getFeatureMap().containsKey("newGame")) { System.out.println("newGame"); this.chatCache.setGameStart(true); }else if (ansAction.getFeatureMap().containsKey("gameBackup")) { System.out.println("gameBackup"); chatCache = new ChatCache(userKey, randKey, chatCache.getGameEnv(), chatCache.getInfoPoint()); flag = ChatCacheController.saveChatCache(chatCache, null); if(flag) solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); else solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); } else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) { System.out.println("loadLastArchive"); ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); if(archiveInfo != null){ System.out.println("存档Id" + archiveInfo.getArchiveId()); }else{ System.out.println("没有找到存档"); } loading(archiveInfo, solution); this.chatCache.setGameStart(true); } else if (ansAction.getFeatureMap().containsKey("loadArchiveBySite")) { System.out.println("loadArchiveBySite"); if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) { site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1]; System.out.println("要读取的存档的地点是:" + site); ArchiveInfo archiveInfo = helper.queryUserLastGameArchiveBySite(userKey, site); loading(archiveInfo, solution); this.chatCache.setGameStart(true); }else{ System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); } } else if(ansAction.getFeatureMap().containsKey("sendArchiveList")){ System.out.println("sendArchiveList"); DataDeliver dataDeliver = new DataDeliver(); JSONObject data = new JSONObject(); List archiveList = helper.queryArchiveByUserKey(userKey); data.put("data", JSONObject.toJSON(archiveList)); data.put("dataType", "archiveList"); data.put("userKey", userKey); dataDeliver.setData(data); dataDeliver.start(); solution.setAnswer("sendData:archiveList:"); //两个冒号,取第二个 } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally{ helper.destroy(); } } private void loading(ArchiveInfo archiveInfo, Solution solution) throws Exception { String keyword = "", site; ChatCache loadCache = null; if (archiveInfo != null) { //如果存在读档,就要将自动跳转和qa的临时数据清空 chatCache.getInfoPoint().put("plot_jump_text", ""); chatCache.getInfoPoint().put("common_answer", ""); loadCache = ChatCacheController.loadChatCache(archiveInfo); //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); this.chatCache.setInfoPoint(loadCache.getInfoPoint()); this.chatCache.setGameEnv(loadCache.getGameEnv()); System.out.println("----------读档中------------"); site = loadCache.getInfoPoint().get("site"); String nextStep = loadCache.getInfoPoint().get(String.format(TASK_CONDITION, site)); String reply = loadCache.getInfoPoint().get(String.format(TASK_REPLY, site)); solution.setAnswer(reply); solution.setNext("nextStep=" + nextStep); this.chatCache.setReload(true); }else{ System.out.println("没有找到该存档"); } } //将文本中存在的变量槽位{npc_xxx}替换成变量值,游戏专用版 //@Override public String varSlotReplace2(String text){ String VARIABLE_REPLACE_PATTERN = "\\$\\{(.*?)}"; Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); String varElements[] = {}, result = ""; String keyword, variable, variableSlot, reply = text; Matcher m = replacePattern.matcher(reply); while (m.find()) { variable = m.group(1); varElements = variable.split("_"); variableSlot = "${" + variable + "}"; switch (varElements[0]){ //如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。 case "globalVariable": reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); case "npc": result = chatCache.getGameEnv().queryNpcAttrByNpcName(varElements[1], varElements[2]); reply = reply.replace(variableSlot, result); case "goods": result = chatCache.getGameEnv().queryGoodsAttrByGoodsName(varElements[1], varElements[2]); reply = reply.replace(variableSlot, result); case "map": System.out.println("地图替换还没写"); default: if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){ reply = reply.replace(variableSlot, curInfoPoint.get(variable)); }else if(chatCache.getInfoPoint().get(variable) != null && !chatCache.getInfoPoint().get(variable).equals("")){ reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); } } } return reply; } public static Matcher findTalker(String reply){ System.out.println(reply); Pattern findTalker = Pattern.compile(TALKER); Matcher m = findTalker.matcher(reply); return m; } static String findFirstTalker(String reply){ String npc = ""; Pattern findTalker = Pattern.compile(TALKER); Matcher m = findTalker.matcher(reply); if(m.find()) { npc = m.group(1); } return npc; } /** * 查看回答文本的说话这是否在当前地点 * 0:没有说话者 * 1:说话者在当前地点 * 2:说话者不在当前地点或者不能说话 * @param reply * @param curInfoPoint * @param historyInfoPoint * @param gameEnv * @param site * @param logWriter * @return */ public static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, String site, LogWriter logWriter){ String npc, location; Matcher m = findTalker(reply); int flag = 1; if(m.find()) { npc = m.group(1); location = gameEnv.queryNpcAttrByNpcName(npc, "location"); System.out.println("location:" + location + ", npc:" + npc); if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ flag = 1; logWriter.record("\"" + reply + "\":匹配", 1); }else { flag = 2; logWriter.record(npc + "不能说话", 1); } }else { logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); flag = 2; } }else{ logWriter.record("\"" + reply + "\":没有npc名",1 ); flag = 0; } return flag; } /** * 查看回答文本的说话这是否在当前地点 * 0:没有说话者 * 1:说话者在当前地点 * 2:说话者不在当前地点或者不能说话 * @param npc * @param site * @param onlineDetect npc是在线类型才可以通过 * @return */ public Boolean canTalk(String npc, String site, Boolean onlineDetect){ String location; Boolean flag = false; location = chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "location"); if( location == null){ return false; } if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if(chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话") == null || chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ if(onlineDetect){ if(isOnlineMode(npc, chatCache.getInfoPoint())){ logWriter.record("\"" + npc + "\":匹配", 1); flag = true; } }else { flag = true; } }else { logWriter.record(npc + "不能说话", 1); } }else { logWriter.record("\"" + npc + "\":" + npc +"不在" + site + ",跳过",1 ); } return flag; } public static String appendTalker(String npc, String text, Map historyInfoPoint, GameEnv gameEnv){ return String.format(TALKER_PATTERN, npc, ASSISTANT_EMOTION) + text; } /** * 判断文本类型 * 1. direct_return:不需要额外处理,直接返回 * 2. less_talker:文本数据不完整,文本开头缺少【%s@%s】 * 3. to_unknown: 用unknown无匹配文本作为回答 * @param reply * @return */ String plotTextFilt(String reply){ String textType, returnText = "plot text filt error", plotLastTalker; String site = chatCache.getInfoPoint().get("site"); textType = textTypeDetect(reply, site); System.out.println("textType:" + textType); switch(textType){ case "direct_return": returnText = reply; break; case "less_talker": //没有npc就添加npc return appendTalker(findRelateTalkers(false).get(0), reply, chatCache.getInfoPoint(), chatCache.getGameEnv()); case "to_unknown": //先设置一个默认答案,在本地点没有可以回答unknown returnText = NO_ONE_CAN_REPLY_UNKNOWN; Set candidates = new HashSet(); Map> npcTextMap = null; String unknownList = "", foundNPC; String fieldList[] = {"unknownTextList", "finalUnknownText"}; String lastReply = chatCache.getInfoPoint().get("lastReply"); //找到上一个回答, plotLastTalker = findTextLastTalker(lastReply, site); for(String unknownField:fieldList){ candidates.clear(); if(userinfo.varInitialMap.get(unknownField) != null) { unknownList = userinfo.varInitialMap.get(unknownField); npcTextMap = unknownTextClassify(unknownList); if(!plotLastTalker.equals("")) { candidates.add(plotLastTalker); } //先找剧情相关的npc foundNPC = foundCandidateText(candidates, npcTextMap); if(!foundNPC.equals("")){ returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); break; }else{ //再找地点相关的npc candidates.addAll(findRelateTalkers(true)); foundNPC = foundCandidateText(candidates, npcTextMap); if(!foundNPC.equals("")){ returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); break; } } } } break; } return returnText; } public String textTypeDetect(String text, String site){ int code = 0; String textType = "to_unknown", npc; Boolean flag = true; npc = findFirstTalker(text); if(text.equals("")){ textType = "to_unknown"; }else if(npc.equals("")) { textType = "less_talker"; }else if(canTalk(npc, site, false)){ textType = "direct_return"; }else{ textType = "to_unknown"; } return textType; } private static Boolean isOnlineMode(String npc, Map historyInfoPoint){ return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); } /** * 找到文本中最后一个可以说话的人, 可以说话是指npc处于玩家所在地点,不是离线模式等 * @param text 文本 * @param site 玩家当前所在地点 * @return */ private String findTextLastTalker(String text, String site){ Matcher m = findTalker(text); String npc, lastTalker = ""; while(m.find()) { //回答unknown文本的npc必须处于在线模式 npc = m.group(1); //处于离线模式 可以说话 相同地点 if(canTalk(npc, site, true)) { //找到最后一个说话且处于离线模式的npc lastTalker = npc; }else{ System.out.println(npc + "是离线模式"); } } return lastTalker; } /** * 找到用来说话的人 * includeSiteNPC 是否包含当前地点的npc */ private List findRelateTalkers(Boolean includeSiteNPC){ String site = chatCache.getInfoPoint().get("site"); String lastReply = chatCache.getInfoPoint().get("lastReply"); List talkers = new ArrayList(); if(lastReply == null) lastReply = ""; String plotLastTalker = findTextLastTalker(lastReply, site); if(!plotLastTalker.equals("")){ talkers.add(plotLastTalker); } if(includeSiteNPC){ List npcList = chatCache.getGameEnv().queryAroundNpcBySite(chatCache.getInfoPoint().get("site")); for(String npc:npcList){ if(canTalk(npc, site, true)){ talkers.add(npc); } } } if(talkers.size() == 0){ talkers.add(chatCache.getInfoPoint().get(ASSISTANT)); } return talkers; } //从unknown文本中提取npc名字 private Map> unknownTextClassify(String unknownText){ String talker; Map> npcTextMap = new HashMap>(); for(String ans:unknownText.split("~")){ talker = findFirstTalker(ans); npcTextMap.putIfAbsent(talker, new ArrayList()); npcTextMap.get(talker).add(ans); } return npcTextMap; } private String foundCandidateText(Set candidates, Map> npcTextMap){ String foundNPC = ""; for(String npc:candidates) { //先看剧情中最后说话的人有没有unknown文本,如果有就。。。 if (npcTextMap.get(npc) != null && npcTextMap.get(npc).size() > 0) { foundNPC = npc; break; } } return foundNPC; } }