package com.qiwu.chatbotbackend.task.utils; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.WorldController; import javax.servlet.ServletContext; import java.io.IOException; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT; import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT_EMOTION; import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; 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.worldController = worldController; this.gameEnv = gameEnv; this.chatCache = chatCache; } @Override public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { Boolean debugFlag = infoPointPreprocessing(receiveParameters, context); //将要去的地点的别名替换为真名 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")); String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if(activeList.length == 0){ historyInfoPoint.put("临时变量condition", "yaobuyao"); }else { historyInfoPoint.put("临时变量condition", activeList[activeList.length-1]); } return debugFlag; } public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ if(userinfo.varInitialMap.get("botType") != null && userinfo.varInitialMap.get("botType").equals("game") && bestMatch.getAnswer().endsWith("开始游戏或者继续游戏")){ try { ChatCacheController.deleteUnuseChatCache(chatKey, context); } catch (Exception e) { e.printStackTrace(); } } //将自动跳转文本、qa文本、查询文本拼接 String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query"}; String queryResult; for(String queryName:queryList){ queryResult = historyInfoPoint.get(queryName); if(queryResult != null && !queryResult.equals("")){ if(queryName.equals("common_answer") && queryResult.equals("no answer")) continue; if(queryName.equals("map_query") || queryName.equals("goods_query") || queryName.equals("npc_query")){ queryResult = "【" + historyInfoPoint.get(PlotConstructor.ASSISTANT) + "@" + PlotConstructor.ASSISTANT_EMOTION + "】" + queryResult; } bestMatch.setAnswer(queryResult + bestMatch.getAnswer() + " " ); historyInfoPoint.put(queryName, ""); } } return true; } 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 = gameEnv.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("玩家"); for (String good : goods) { sb.append("+").append(good); } keyword = sb.toString(); }else{ keyword = gameEnv.queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]); } } }else if (actionName.startsWith("goods_")) { if (nameSeries.length == 4) { keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[2], nameSeries[3]); System.out.println("return" + keyword); }else if (nameSeries.length == 3){ keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); } }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(" + 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("返回:" + 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,就专门交给world处理 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; } String returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint); updateValue = returnStr; } catch (Exception e) { e.printStackTrace(); updateValue = "游戏模块处理出错"; } } historyInfoPoint.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; } @Override public void extraOperation(Condition ansCondition, 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(ansCondition.featureMap.containsKey("newGame")) { System.out.println("newGame"); this.chatCache.setGameStart(true); }else if (ansCondition.featureMap.containsKey("gameBackup")) { System.out.println("gameBackup"); if(! userKey.equals(randKey)) { //两者不同时表示用户已登录,才有权限存档 chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint); flag = ChatCacheController.saveChatCache(chatCache, null); if(flag) solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); else solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); }else{ solution.setAnswer("体验作品时无法存档哦,请下载我们的app体验更多功能"); solution.setNext(""); //可能存在问题,估计要一个空格 } } else if (ansCondition.featureMap.containsKey("loadLastArchive")) { System.out.println("loadLastArchive"); ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); loading(archiveInfo, solution); this.chatCache.setGameStart(true); } else if (ansCondition.featureMap.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); } } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally{ helper.destroy(); } } private void loading(ArchiveInfo archiveInfo, Solution solution){ String keyword = "", site; ChatCache loadCache = null; //如果存在读档,就要将自动跳转和qa的临时数据清空 historyInfoPoint.put("plot_jump_text", ""); historyInfoPoint.put("common_answer", ""); if (archiveInfo != null) { try { loadCache = ChatCacheController.loadChatCache(archiveInfo); } catch (Exception e) { System.out.println("从本地加载存档失败"); solution.setAnswer("从本地加载存档失败"); e.printStackTrace(); } 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(PlotConstructor.TASK_CONDITION, site)); String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor.TASK_REPLY, site)); solution.setAnswer(reply); solution.setNext("nextStep=" + nextStep); }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, historyInfoPoint.get(variable)); case "npc": result = gameEnv.queryNpcAttrByNpcName(varElements[1], varElements[2]); reply = reply.replace(variableSlot, result); case "goods": result = gameEnv.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(historyInfoPoint.get(variable) != null && !historyInfoPoint.get(variable).equals("")){ reply = reply.replace(variableSlot, historyInfoPoint.get(variable)); } } } return reply; } }