From 78a9b98a013b44b3d870c5ff1720074385efb3b3 Mon Sep 17 00:00:00 2001 From: zhouwei <849588297@qq.com> Date: Wed, 4 Feb 2026 13:21:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/robot/mj/JiQiRens.java | 1786 ----------------- .../java/robot/mj/RobotConnectionManager.java | 152 +- 2 files changed, 136 insertions(+), 1802 deletions(-) delete mode 100644 robots/majiang/robot_mj_cs/src/main/java/robot/mj/JiQiRens.java diff --git a/robots/majiang/robot_mj_cs/src/main/java/robot/mj/JiQiRens.java b/robots/majiang/robot_mj_cs/src/main/java/robot/mj/JiQiRens.java deleted file mode 100644 index 8f89801..0000000 --- a/robots/majiang/robot_mj_cs/src/main/java/robot/mj/JiQiRens.java +++ /dev/null @@ -1,1786 +0,0 @@ -/* -package robot.mj; - - -import com.game.Util; -import com.taurus.core.entity.ITArray; -import com.taurus.core.entity.ITObject; -import com.taurus.core.entity.TObject; -import com.taurus.core.events.Event; -import com.taurus.core.events.IEventListener; -import com.taurus.core.plugin.database.DataBase; -import com.taurus.core.plugin.redis.Redis; -import com.taurus.core.util.ICallback; -import com.taurus.core.util.Logger; -import com.taurus.core.util.StringUtil; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; -import taurus.client.Message; -import taurus.client.MessageResponse; -import taurus.client.SocketCode; -import taurus.client.TaurusClient; -import taurus.client.business.AccountBusiness; -import taurus.client.business.GroupRoomBusiness; -import taurus.util.ChangShaSuanFaTest; -import taurus.util.TinHuChi; - -import java.sql.SQLException; -import java.util.*; -import java.util.stream.Collectors; - -public class JiQiRens { - - - private final static Logger log; - - static { - log = Logger.getLogger(JiQiRens.class); - } - - - // 扣点点玩家手牌 - public static List cardInhand = new ArrayList(); - - //使用数量 - public static Map count = new HashMap(); - - //扣点点别人打的牌 - private String card = ""; - - // 玩家座位号 - public static int seat = 0; - // 玩家ID - // 登录密码 - public static String password = "123456"; - // 会话标识 - private String session = ""; - // 访问令牌 - public String token = ""; - // 玩法ID - public String wanfaId = ""; - - public int tuichutime = 0; - - // 客户端连接对象 - private TaurusClient client = null; - - private HuNanHongZhong huNanHongZhong = new HuNanHongZhong(); - - private HuNanZhuanZhuan huNanZhuanZhuan = new HuNanZhuanZhuan(); - - private HuNanFangPaoFa huNanFangPaoFa = new HuNanFangPaoFa(); - - private HuNanPaoDeKuai huNanPaoDeKuai = new HuNanPaoDeKuai(); - - private HuNanChangSha huNanChangSha = new HuNanChangSha(); - - // private HuNanChangShaNew huNanChangShaNew = new HuNanChangShaNew();//新的机器人处理对象 - - - private TinHuChi tinHuChi = new TinHuChi(); - - - private Map> playerOutcardsMap = new HashMap<>(); - - - private Map> playerchisMap = new HashMap<>(); - - private Map> playerpengsMap = new HashMap<>(); - - private Map> playermingsMap = new HashMap<>(); - - private Map> playerzisMap = new HashMap<>(); - - - - //圈子id -// public static int groupId = 0; - - //房间id -// public static String roomId = ""; - - - */ -/** - * TCP测试方法,用于建立客户端连接并处理游戏事件 - * - * @throws Exception - *//* - - public void tcp_test(int playerId, Integer pid, int groupId) throws Exception { - Jedis jedis11 = Redis.use("group1_db11").getJedis(); - Jedis jedis0 = Redis.use().getJedis(); - String playKey = "g{" + groupId + "}:play:" + pid; - - - try { - //todo 获取所有房间 - Set roomIds = jedis0.keys("room:*"); -// Set roomIds = scanRooms(jedis0, "room:*"); - String roomKey = ""; - //todo 获取玩法id对应的游戏id - if (jedis11.hget(playKey, "leftover_robot") != null) { - if (wanfaId.equals("")) { - //todo 通过房间id获取玩法id - Boolean is_match = false; - for (String id : roomIds) { - String roomId = id.substring(id.indexOf(":") + 1); - roomKey = "room:" + roomId; - String gpid = jedis0.hget(roomKey, "gpid"); - String players = jedis0.hget(roomKey, "players"); - - if (gpid != null) { - if (Integer.parseInt(gpid) == pid) { - is_match = true; - } -// if (players.equals("[]")) { -// is_match = false; -// } - } - } - if (roomIds.size() == 0 || !is_match) { - ITObject object = null; - AccountBusiness accountBusiness = null; - accountBusiness = new AccountBusiness(); - // 登录获取session跟token - - if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) { - - - Set keys1 = jedis0.keys("{user}:" + playerId + "_token"); - if (keys1 == null) { - object = accountBusiness.idPasswordLogin(playerId, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } else { - Set keys = jedis0.smembers("{user}:" + playerId + "_token"); - List keyList = new ArrayList<>(keys); - session = "{user}:" + playerId; - token = keyList.get(0); - - } - } else { - //todo 登录机器人账号 - object = accountBusiness.idPasswordLogin(playerId, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } - - - //todo 匹配房间 - Object room = GroupRoomBusiness.matchRoom(groupId, pid, session, "Android", false); - String game = jedis0.hget(String.valueOf(room), "game"); -// ITObject game_info = roomInfo.getTObject("game_info"); -// Integer game_id = game_info.getInt("game_id"); - wanfaId = String.valueOf(game); - - } - } - //满人房间玩法 - List manrenwanfa = new ArrayList<>(); - - String[] playerIds2 = null; - for (String id : roomIds) { - String roomId = id.substring(id.indexOf(":") + 1); - String roomKeys = "room:" + roomId; - if (jedis0.hget(roomKeys, "players") != null) { - String players = jedis0.hget(roomKeys, "players"); - String players1 = players.substring(1, players.length() - 1); - playerIds2 = players1.split(","); - if (playerIds2.length == 2) { - manrenwanfa.add(jedis0.hget(roomKeys, "gpid")); - } - } - } - - - List> xuyaojianlifangjian = new ArrayList<>(); - for (String id : roomIds) { - String roomId = id.substring(id.indexOf(":") + 1); - String roomKeys = "room:" + roomId; - if (jedis0.hget(roomKeys, "players") != null && jedis0.hget(roomKeys, "gpid") != null) { - String gpid = jedis0.hget(roomKeys, "gpid"); - String players = jedis0.hget(roomKeys, "players"); - if (players.equals("[]")) { - xuyaojianlifangjian.add(Arrays.asList(gpid, players)); - } else { - String players1 = players.substring(1, players.length() - 1); - String[] playerIds9 = players1.split(","); - xuyaojianlifangjian.add(Arrays.asList(gpid, String.valueOf(playerIds9.length))); - } - } - - if ( jedis0.hget(roomKeys, "gpid") != null){ - String gpid = jedis0.hget(roomKeys, "gpid"); - if (jedis0.hget(roomKeys, "players") == null) { - xuyaojianlifangjian.add(Arrays.asList(gpid, "5")); - - } - } - - } - - - - Set excludedKeys = xuyaojianlifangjian.stream() - .filter(list -> { - String value = list.get(1); - return value.equals("[]") || value.equals("1") || value.equals("5"); - }) - .map(list -> list.get(0)) - .collect(Collectors.toSet()); - - - List> filteredResult = xuyaojianlifangjian.stream() - .filter(list -> manrenwanfa.contains(list.get(0))) - .filter(list -> !excludedKeys.contains(list.get(0))) - .collect(Collectors.toList()); - - - List keys10 = filteredResult.stream() - .map(list -> list.get(0)) // 获取每个list的第一个元素(key) - .collect(Collectors.toList()); - - - - - - - List robotIdsList1 = new ArrayList<>(); - - String sql3 = String.format("SELECT id FROM `account` WHERE jiqiren=9998 and start = 0"); - ITArray robotId3 = DataBase.use().executeQueryByTArray(sql3); - - for (int j = 0; j < robotId3.size(); j++) { - robotIdsList1.add(robotId3.getTObject(j).getInt("id")); - } - - - int userIndex = 0; - for (String s : keys10) { - - String groupKeys = "g{" + groupId + "}:play:" + s; - if (jedis11.hget(groupKeys, "leftover_robot") != null) { - String shengyu = jedis11.hget(groupKeys, "leftover_robot"); - if (Integer.parseInt(shengyu) > 0 && userIndex < robotIdsList1.size()) { - Integer playerid = robotIdsList1.get(userIndex); - userIndex++; - - ITObject object = null; - AccountBusiness accountBusiness = null; - accountBusiness = new AccountBusiness(); - - // 登录获取session跟token - if (jedis0.keys("{user}:" + playerid + "_token").size() != 0) { - Set keys1 = jedis0.keys("{user}:" + playerid + "_token"); - if (keys1 == null) { - object = accountBusiness.idPasswordLogin(playerid, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } else { - Set keys = jedis0.smembers("{user}:" + playerid + "_token"); - List keyList = new ArrayList<>(keys); - session = "{user}:" + playerid; - token = keyList.get(0); - } - } else { - object = accountBusiness.idPasswordLogin(playerid, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } - - - Object roomkey = GroupRoomBusiness.matchRoom(groupId, Integer.parseInt(s), session, "Android", false); - String game = jedis0.hget(String.valueOf(roomkey), "game"); - wanfaId = String.valueOf(game); - } - } - } - - String[] playerIds = null; - String leftover_robot = jedis11.hget(playKey, "leftover_robot"); - if (Integer.parseInt(leftover_robot) > 0) { - - - - - //真人等机器人游戏id赋值 - for (String id : roomIds) { - String roomId = id.substring(id.indexOf(":") + 1); - roomKey = "room:" + roomId; - - String players = jedis0.hget(roomKey, "players"); - String gpid = jedis0.hget(roomKey, "gpid"); - - String roKey = "g{" + groupId + "}:play:" + gpid; - String leftover_robot1 = jedis11.hget(roKey, "leftover_robot"); - - if (players != null && !players.equals("[]")) { - players = players.substring(1, players.length() - 1); - playerIds = players.split(","); - List robotIdsList = new ArrayList<>(); - //拿到所有的机器人 - String sql2 = String.format("SELECT id FROM `account` WHERE jiqiren=9998"); - ITArray robotId2 = DataBase.use().executeQueryByTArray(sql2); - - for (int j = 0; j < robotId2.size(); j++) { - robotIdsList.add(robotId2.getTObject(j).getInt("id")); - } - for (String s : playerIds) { - - if (leftover_robot1 != null) { - if (playerIds.length == 1 && !robotIdsList.contains(Integer.parseInt(s)) && Integer.parseInt(leftover_robot1) > 0) { - - wanfaId = jedis0.hget(roomKey, "game"); - - } - } - } - } - } - - - if (wanfaId.equals("")) { - for (String id : roomIds) { - String roomId = id.substring(id.indexOf(":") + 1); - String roomKeys1 = "room:" + roomId; - if (jedis0.hget(roomKeys1, "gpid") != null) { - String gpid = jedis0.hget(roomKeys1, "gpid"); - - if (pid == Integer.parseInt(gpid)) { - wanfaId = jedis0.hget(roomKeys1, "game"); - } - } - } - } - //todo 根据玩法id 创建tcp连接 - System.out.println(wanfaId); - if ("22".equalsIgnoreCase(wanfaId)) { //湖南红中麻将 - client = new TaurusClient("8.138.242.190:6421", "game", TaurusClient.ConnectionProtocol.Tcp); - } - - if ("10".equalsIgnoreCase(wanfaId)) { - client = new TaurusClient("127.0.0.1:6311", "game", TaurusClient.ConnectionProtocol.Tcp); - } -// - if ("66".equalsIgnoreCase(wanfaId)) { - client = new TaurusClient("8.138.242.190:6841", "game", TaurusClient.ConnectionProtocol.Tcp); - } - client.connect(); -// } - - //连接根据不同的玩法id 配置不同的连接 - - - //这里是机器人主动进入空房间 - Set roomIds1 = jedis0.keys("room:*"); - - - for (String id : roomIds1) { - String roomId = id.substring(id.indexOf(":") + 1); - roomKey = "room:" + roomId; - if (jedis0.hget(roomKey, "gpid") != null) { - String gpid = jedis0.hget(roomKey, "gpid"); - String playKey2 = "g{" + groupId + "}:play:" + gpid; - - String roomPidKey = null; - boolean flag = false; - if (jedis0.hget(roomKey, "players") == null) { - - - roomKey = "room:" + roomId; - roomPidKey = jedis0.hget(roomKey, "gpid"); - - if (jedis0.hget(roomKey, "game") != null) { - String gameId = jedis0.hget(roomKey, "game"); - - if (wanfaId.equals(gameId)) { - - flag = true; - } - } - } - - String players = jedis0.hget(roomKey, "players"); - - - if (jedis11.hget(playKey2, "leftover_robot") != null) { - String leftover_robot1 = jedis11.hget(playKey2, "leftover_robot"); - if (players == null && Integer.parseInt(roomPidKey) == pid && Integer.parseInt(leftover_robot1) > 0 && flag) { - - - ITObject object = null; - AccountBusiness accountBusiness = null; - accountBusiness = new AccountBusiness(); - // 登录获取session跟token - if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) { - Set keys1 = jedis0.keys("{user}:" + playerId + "_token"); - if (keys1 == null) { - object = accountBusiness.idPasswordLogin(playerId, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } else { - Set keys = jedis0.smembers("{user}:" + playerId + "_token"); - List keyList = new ArrayList<>(keys); - session = "{user}:" + playerId; - token = keyList.get(0); - } - } else { - object = accountBusiness.idPasswordLogin(playerId, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } - - String group = jedis0.hget(roomKey, "group"); - ITObject roomInfos = GroupRoomBusiness.joinRoom(Integer.parseInt(group), roomKey, session, null); - joinRoom(playerId); //进入房间 - ready(); //准备 - String playKey1 = "g{" + groupId + "}:play:" + roomPidKey; - - -// //增加使用数量 - Integer key = Integer.valueOf(roomPidKey); - - count.put(key, count.getOrDefault(key, 0) + 1); - - - jedis11.hincrBy(playKey1, "leftover_robot", -1); - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 1, playerId); - DataBase.use().executeUpdate(sql); - - - } - } - } - - - roomKey = "room:" + roomId; - if (jedis0.hget(roomKey, "gpid") != null) { - String gpid = jedis0.hget(roomKey, "gpid"); - String playKey2 = "g{" + groupId + "}:play:" + gpid; - - String roomPidKey = null; - boolean flag = false; - if (jedis0.hget(roomKey, "players") != null) { - if (jedis0.hget(roomKey, "players").equals("[]")) { - - roomKey = "room:" + roomId; - roomPidKey = jedis0.hget(roomKey, "gpid"); - if (jedis0.hget(roomKey, "game") != null) { - - String gameId = jedis0.hget(roomKey, "game"); - if (wanfaId.equals(gameId)) { - flag = true; - } - } - } - String players = jedis0.hget(roomKey, "players"); - - - if (jedis11.hget(playKey2, "leftover_robot") != null) { - String leftover_robot1 = jedis11.hget(playKey2, "leftover_robot"); - if (players.equals("[]") && Integer.parseInt(roomPidKey) == pid && Integer.parseInt(leftover_robot1) > 0 && flag) { - - ITObject object = null; - AccountBusiness accountBusiness = null; - accountBusiness = new AccountBusiness(); - // 登录获取session跟token - if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) { - Set keys1 = jedis0.keys("{user}:" + playerId + "_token"); - if (keys1 == null) { - object = accountBusiness.idPasswordLogin(playerId, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } else { - Set keys = jedis0.smembers("{user}:" + playerId + "_token"); - List keyList = new ArrayList<>(keys); - session = "{user}:" + playerId; - token = keyList.get(0); - - } - } else { - object = accountBusiness.idPasswordLogin(playerId, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } - - String group = jedis0.hget(roomKey, "group"); - ITObject roomInfos = GroupRoomBusiness.joinRoom(Integer.parseInt(group), roomKey, session, null); - joinRoom(playerId); //进入房间 - ready(); //准备 - String playKey1 = "g{" + groupId + "}:play:" + roomPidKey; - - -// //增加使用数量 - Integer key = Integer.valueOf(roomPidKey); - - count.put(key, count.getOrDefault(key, 0) + 1); - - - jedis11.hincrBy(playKey1, "leftover_robot", -1); - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 1, playerId); - DataBase.use().executeUpdate(sql); - - - } - } - - } - - } - - - } - - // 添加事件监听器处理网络消息 - client.addEventListener(TaurusClient.NetClientEvent.OnEvent, new IEventListener() { - @Override - public void handleEvent(Event event) { - - // 获取 msg - Message message = (Message) event.getParameter("msg"); - if (message == null) { - return; - } - - ITObject param = message.param; - - //回调协议号 - String command = message.command; - - //根据玩法id 调用不同的回调 - if (StringUtil.isNotEmpty(command)) { - if ("93".equalsIgnoreCase(wanfaId)) { //扣点点 - if ("812".equalsIgnoreCase(command)) { //出牌广播 - sleepTime(1000); - drawCard(command, message); - } else if ("820".equalsIgnoreCase(command)) { - changePlayer(command, message); - } else if ("819".equalsIgnoreCase(command)) { //摸牌 - getCard(command, message); - } else if ("811".equalsIgnoreCase(command)) { //初始化手牌 - cardInHead(command, message, wanfaId); - } else if ("813".equalsIgnoreCase(command)) { //出牌,牌权 - sleepTime(2000); - outCard(command, message, wanfaId); - } else if ("817".equalsIgnoreCase(command)) { - ready(); - //杠碰胡通知协议 - } else if ("814".equalsIgnoreCase(command)) { - sleepTime(2000); - actionCard(param); - //doGang杠后补牌 补杠事件 - } else if ("838".equalsIgnoreCase(command)) { - sleepTime(2000); - buGang(param); - } - } - else if ("66".equalsIgnoreCase(wanfaId)) {//跑的快 - if ("2011".equalsIgnoreCase(command)) { //跑的快 初始化手牌 - huNanPaoDeKuai.paoDeKuaiCardInHead(param, client); - } else if ("2021".equalsIgnoreCase(command)) { //出牌广播 - huNanPaoDeKuai.paoDekuaiChupaiGuangBo(param); - } else if ("2004".equalsIgnoreCase(command)) { //出牌提示事件,牌权 - Integer player = param.getInt("player"); - Integer seat1 = param.getInt("seat"); - - if (seat1 != null) { - huNanPaoDeKuai.seat = seat1; - } - - //出牌 - huNanPaoDeKuai.outCard(client); - } else if ("2007".equalsIgnoreCase(command)) { //结算准备 - //type为1 为大结算 type为0为小结算 - Integer type = param.getInt("type"); - - if (type == 0) { - huNanPaoDeKuai.getSeatRemainHistory().clear(); - huNanPaoDeKuai.getPaoDekuaiCardInhand().clear(); - ITArray card_list = huNanPaoDeKuai.getCard_list().getTArray("card_list"); - card_list.clear(); - ready(); - } - - if (type == 1) { - Jedis jedis11s = Redis.use("group1_db11").getJedis(); - try { - String key = "g{" + groupId + "}:play:" + pid; - jedis11s.hincrBy(key, "leftover_robot", 1); - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId); - try { - DataBase.use().executeUpdate(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - jedis11s.close(); - } - } - - } else if ("2009".equalsIgnoreCase(command)) { - Jedis jedis21 = Redis.use().getJedis(); - sleepTime(3000); - - ITObject params = TObject.newInstance(); - String[] playerIds2 = null; - - - Set roomIds = jedis21.keys("room:*"); - String roomKey = ""; - //拿到所有的机器人 - List robotIdsList = new ArrayList<>(); - String sql2 = "SELECT id FROM `account` WHERE jiqiren=9998"; - ITArray robotId2 = null; - try { - robotId2 = DataBase.use().executeQueryByTArray(sql2); - } catch (SQLException e) { - e.printStackTrace(); - } - for (int j = 0; j < Objects.requireNonNull(robotId2).size(); j++) { - robotIdsList.add(robotId2.getTObject(j).getInt("id")); - } - - - for (String roomId : roomIds) { - String roomId1 = roomId.substring(roomId.indexOf(":") + 1); - roomKey = "room:" + roomId1; - - if (jedis21.hget(roomKey, "players") != null) { - String players = jedis21.hget(roomKey, "players"); - if (!players.equals("[]")) { - players = players.substring(1, players.length() - 1); - playerIds2 = players.split(","); - - - if (playerIds2.length == 1) { - for (String s : playerIds2) { - if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人 - String gpid = jedis21.hget(roomKey, "gpid"); - String gpId = jedis21.hget(roomKey, "group"); - String key = "g{" + gpId + "}:play:" + gpid; - if (!players.equals("[]") && pid == Integer.parseInt(gpid)) { - - - if (JiQiRens.count != null && JiQiRens.count.containsKey(Integer.parseInt(gpid))) { - Integer currentValue = JiQiRens.count.get(Integer.parseInt(gpid)); - if (currentValue > 0) { - JiQiRens.count.put(Integer.parseInt(gpid), currentValue - 1); - } - } - - - Jedis jedis20 = Redis.use("group1_db11").getJedis(); - - jedis20.hincrBy(key, "leftover_robot", 1); - jedis20.close(); - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, Integer.parseInt(s)); - - try { - DataBase.use().executeUpdate(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - - client.send("1005", params, response -> { - - }); - - } - } - } - } - } - } - } - - jedis21.close(); - - } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用 - Set roomIds = scanRooms(jedis0, "room:*"); - String[] playerIds = null; - for (String roomId : roomIds) { - String rid = roomId.substring(roomId.indexOf(":") + 1); - String roomKey = "room:" + rid; - if (jedis0.hget(roomKey, "players") != null) { - String players = jedis0.hget(roomKey, "players"); - if (!players.equals("[]")) { - players = players.substring(1, players.length() - 1); - playerIds = players.split(","); - for (String pyids : playerIds) { - if (Integer.parseInt(pyids) == playerId) { - jedis0.del(roomId); - } - } - } - } - } - } else if ("2031".equalsIgnoreCase(command)) { - ITObject params = TObject.newInstance(); - params.putInt("id", 0); - client.send("1015", params, response -> { - - }); - - } - } else if ("22".equalsIgnoreCase(wanfaId)) { //湖南红中麻将 - - if ("812".equalsIgnoreCase(command)) { //出牌广播 - HuNanHongZhong.drawCard(command, message); - } else if ("811".equalsIgnoreCase(command)) {//初始化手牌 - huNanHongZhong.cardInHead(command, message, client); - } else if ("819".equalsIgnoreCase(command)) { //摸牌 - huNanHongZhong.getCard(command, message); - } else if ("813".equalsIgnoreCase(command)) { //出牌,牌权 - huNanHongZhong.outCard(client); - } else if ("817".equalsIgnoreCase(command)) {//结算 - huNanHongZhong.getHongZhongCardInhand().clear(); - huNanHongZhong.getChuGuoCardInhand().clear(); - - Integer type = param.getInt("type"); - if (type == 1 || type == 2) { //为1为大结算 为2为解散 - Jedis jedis11s = Redis.use("group1_db11").getJedis(); - try { - String key = "g{" + groupId + "}:play:" + pid; - jedis11s.hincrBy(key, "leftover_robot", 1); -// - if (count != null && count.containsKey(pid)) { - Integer currentValue = count.get(pid); - if (currentValue > 0) { - count.put(pid, currentValue - 1); - } - } - - - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId); - try { - DataBase.use().executeUpdate(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - jedis11s.close(); - } - - if (count != null && count.containsKey(pid)) { - Integer value = count.get(pid); - - // 如果找到了对应的 pid - String shangxianRobot = jedis11.hget(playKey, "shangxian_robot"); - String leftoverRobot = jedis11.hget(playKey, "leftover_robot"); - - if (shangxianRobot != null && leftoverRobot != null) { - if (value == 0) { - jedis11.hset(playKey, "leftover_robot", shangxianRobot); - } - } - } - } -// playerState.pongGroups.clear();; -// playerState.handCards.clear(); -// playerState.chiGroups.clear(); -// playerState.gangGroups.clear();; - - - ready(); - } else if ("2009".equalsIgnoreCase(command)) { - Jedis jedis21 = Redis.use().getJedis(); - sleepTime(3000); - ITObject params = TObject.newInstance(); - String[] playerIds2 = null; - - - Set roomIds = jedis21.keys("room:*"); - String roomKey = ""; - //拿到所有的机器人 - List robotIdsList = new ArrayList<>(); - String sql2 = "SELECT id FROM `account` WHERE jiqiren=9998"; - ITArray robotId2 = null; - try { - robotId2 = DataBase.use().executeQueryByTArray(sql2); - } catch (SQLException e) { - e.printStackTrace(); - } - for (int j = 0; j < Objects.requireNonNull(robotId2).size(); j++) { - robotIdsList.add(robotId2.getTObject(j).getInt("id")); - } - - - for (String roomId : roomIds) { - String roomId1 = roomId.substring(roomId.indexOf(":") + 1); - roomKey = "room:" + roomId1; - - if (jedis21.hget(roomKey, "players") != null) { - String players = jedis21.hget(roomKey, "players"); - if (!players.equals("[]")) { - players = players.substring(1, players.length() - 1); - playerIds2 = players.split(","); - - - if (playerIds2.length == 1) { - for (String s : playerIds2) { - if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人 - String gpid = jedis21.hget(roomKey, "gpid"); - String gpId = jedis21.hget(roomKey, "group"); - String key = "g{" + gpId + "}:play:" + gpid; - if (!players.equals("[]") && pid == Integer.parseInt(gpid)) { - - - if (JiQiRens.count != null && JiQiRens.count.containsKey(Integer.parseInt(gpid))) { - Integer currentValue = JiQiRens.count.get(Integer.parseInt(gpid)); - if (currentValue > 0) { - JiQiRens.count.put(Integer.parseInt(gpid), currentValue - 1); - } - } - - - Jedis jedis20 = Redis.use("group1_db11").getJedis(); - - jedis20.hincrBy(key, "leftover_robot", 1); - jedis20.close(); - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, Integer.parseInt(s)); - - try { - DataBase.use().executeUpdate(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - - client.send("1005", params, response -> { - - }); - - } - } - } - } - } - } - } - - jedis21.close(); - - } else if ("814".equalsIgnoreCase(command)) {//杠碰胡通知协议 -// sleepTime(2000); - huNanHongZhong.actionCard(param, client); - } else if ("820".equalsIgnoreCase(command)) { - HuNanHongZhong.changePlayer(command, message); - } else if ("815".equalsIgnoreCase(command)) { //服务器通知客户端有玩家执行了操作 - huNanHongZhong.shanchuchuguopai(param); - } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用 -// Jedis jedis11s = Redis.use("group1_db11").getJedis(); -// try { -// String key = "g{" + groupId + "}:play:" + pid; -// jedis11s.hincrBy(key, "leftover_robot", 1); -// String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId); -// DataBase.use().executeUpdate(sql); - Set roomIds = scanRooms(jedis0, "room:*"); - String[] playerIds = null; - for (String roomId : roomIds) { - String rid = roomId.substring(roomId.indexOf(":") + 1); - String roomKey = "room:" + rid; - if (jedis0.hget(roomKey, "players") != null) { - String players = jedis0.hget(roomKey, "players"); - if (!players.equals("[]")) { - players = players.substring(1, players.length() - 1); - playerIds = players.split(","); - for (String pyids : playerIds) { - if (Integer.parseInt(pyids) == playerId) { - jedis0.del(roomId); - } - } - } - } - } - - } - } else if ("17".equalsIgnoreCase(wanfaId)) { //字牌放炮罚 - - if ("811".equalsIgnoreCase(command)) { //初始化手牌 - huNanFangPaoFa.cardInHead(command, message, client); - - } else if ("819".equalsIgnoreCase(command)) { //摸牌 - huNanFangPaoFa.getCard(command, message); - } else if ("813".equalsIgnoreCase(command)) { //出牌 牌权 - sleepTime(1500); - huNanFangPaoFa.outCard(client); - } else if ("812".equalsIgnoreCase(command)) { //出牌广播 - HuNanFangPaoFa.drawCard(command, message); - } else if ("814".equalsIgnoreCase(command)) { //可执行的 操作 吃碰 偎提胡 - huNanFangPaoFa.actionCard(param, client); - } else if ("817".equalsIgnoreCase(command)) { //结算 - huNanFangPaoFa.getFangPaoFaCardInhand().clear(); - ready(); - } else if ("822".equalsIgnoreCase(command)) { //放跑提示 - - HuNanFangPaoFa.fangPaoTipEvent(message, client); - } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用 - try { - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId); - DataBase.use().executeUpdate(sql); - - } catch (SQLException e) { - - } - } - } - else if ("108".equalsIgnoreCase(wanfaId)) {//转转麻将 - if ("811".equalsIgnoreCase(command)) {//初始化收手牌 - huNanZhuanZhuan.cardInHead(command, message, client); - } else if ("812".equalsIgnoreCase(command)) {//出牌广播 - HuNanZhuanZhuan.drawCard(command, message); - } else if ("819".equalsIgnoreCase(command)) {//摸牌 - - huNanZhuanZhuan.getCard(command, message); - } else if ("813".equalsIgnoreCase(command)) {//出牌提示 -// sleepTime(1500); - huNanZhuanZhuan.outCard(client); - } else if ("814".equalsIgnoreCase(command)) {//放招提示 - huNanZhuanZhuan.actionCard(param, client); - } else if ("817".equalsIgnoreCase(command)) {//结算 - huNanZhuanZhuan.getZhuanZhuanCardInhand().clear(); - huNanZhuanZhuan.getZhuanZhuanchuguopai().clear(); - ready(); - } else if ("815".equalsIgnoreCase(command)) { //服务器通知客户端有玩家执行了操作 - huNanZhuanZhuan.shanchuchuguopai(param); - } else if ("820".equalsIgnoreCase(command)) {//换牌提示 - HuNanZhuanZhuan.changePlayer(command, message); - } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用 - try { - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId); - DataBase.use().executeUpdate(sql); - } catch (SQLException e) { - - } - } - } - else if ("10".equalsIgnoreCase(wanfaId)) { - //长沙麻将 机器人处理事件 - - //[TCP->822] data:{"tip_list":[{"type":8,"id":1,"opcard":[],"weight":8,"card":0}],"types":[{"type":21,"value":1}]} - //板胡Event [TCP->823] data:{"type":8,"seat":1,"data":[{"opcard":[204,204,204,108,108,108],"type":21,"value":1}]} - if ("811".equalsIgnoreCase(command)) {//初始化收手牌 - huNanChangSha.cardInHead(command, message, client); - } else if ("812".equalsIgnoreCase(command)) {//出牌广播 - //{"opzicards":[{"opzicards":[],"playerId":101555}],"opmingcards":[{"opmingcards":[],"playerId":101555}],"outcard_map":[{"outcards":[209,205],"playerId":101555},{"outcards":[],"playerId":112233}],"card":205,"opchicards":[{"opchicards":[105,103],"playerId":101555}],"oppengcards":[{"oppengcards":[],"playerId":101555}],"seat":1} - ITArray outcard_map = param.getTArray("outcard_map"); - ITArray opchicards = param.getTArray("opchicards"); - ITArray oppengcards = param.getTArray("oppengcards"); - ITArray opmingcards = param.getTArray("opmingcards"); - ITArray opzicards = param.getTArray("opzicards"); - - // 清空旧数据,用新数据完全覆盖 - playerOutcardsMap.clear(); - playerchisMap.clear(); - playerpengsMap.clear(); - playermingsMap.clear(); - playerzisMap.clear(); - //出过的牌 - if (outcard_map != null) { - for (int i = 0; i < outcard_map.size(); i++) { - ITObject playerData = outcard_map.getTObject(i); - int playerId = playerData.getInt("playerId"); - ITArray outcardsArray = playerData.getTArray("outcards"); - - // 转换为List - List outcardsList = new ArrayList<>(); - for (int j = 0; j < outcardsArray.size(); j++) { - outcardsList.add(outcardsArray.getInt(j)); - } - - // 存储到Map中(覆盖旧数据) - playerOutcardsMap.put(playerId, outcardsList); - - } - } - - //吃的牌 - if (opchicards != null) { - for (int i = 0; i < opchicards.size(); i++) { - ITObject playerData = opchicards.getTObject(i); - int playerId = playerData.getInt("playerId"); - ITArray outchiArray = playerData.getTArray("opchicards"); - - List outchiList = new ArrayList<>(); - for (int j = 0; j < outchiArray.size(); j++) { - outchiList.add(outchiArray.getInt(j)); - } - playerchisMap.put(playerId, outchiList); - } - } - - //碰的牌 - if (oppengcards != null) { - for (int i = 0; i < oppengcards.size(); i++) { - ITObject playerData = oppengcards.getTObject(i); - int playerId = playerData.getInt("playerId"); - ITArray outpengArray = playerData.getTArray("oppengcards"); - - List outpengList = new ArrayList<>(); - for (int j = 0; j < outpengArray.size(); j++) { - outpengList.add(outpengArray.getInt(j)); - } - playerpengsMap.put(playerId, outpengList); - } - } - - //明杠的牌 - if (opmingcards != null) { - for (int i = 0; i < opmingcards.size(); i++) { - ITObject playerData = opmingcards.getTObject(i); - int playerId = playerData.getInt("playerId"); - ITArray outmingArray = playerData.getTArray("opmingcards"); - - List outmingList = new ArrayList<>(); - for (int j = 0; j < outmingArray.size(); j++) { - outmingList.add(outmingArray.getInt(j)); - } - playermingsMap.put(playerId, outmingList); - } - } - - //暗杠的牌 - if (opzicards != null) { - for (int i = 0; i < opzicards.size(); i++) { - ITObject playerData = opzicards.getTObject(i); - int playerId = playerData.getInt("playerId"); - ITArray outziArray = playerData.getTArray("opzicards"); - - List outziList = new ArrayList<>(); - for (int j = 0; j < outziArray.size(); j++) { - outziList.add(outziArray.getInt(j)); - } - playerzisMap.put(playerId, outziList); - } - } - - HuNanChangSha.drawCard(command, message); - } else if ("819".equalsIgnoreCase(command)) { - //摸牌 - huNanChangSha.getCard(command, message); - } else if ("813".equalsIgnoreCase(command)) {//出牌提示 - huNanChangSha.outCard(client,playerOutcardsMap,playerchisMap,playerpengsMap,playermingsMap,playerzisMap); - } else if ("814".equalsIgnoreCase(command)) { - //放招提示 - huNanChangSha.actionCard(param, client); - - } else if ("2009".equalsIgnoreCase(command)) { - Jedis jedis22 = Redis.use().getJedis(); - sleepTime(3000); - - ITObject params = TObject.newInstance(); - String[] playerIds2 = null; - - - Set roomIds = jedis22.keys("room:*"); - String roomKey = ""; - //拿到所有的机器人 - List robotIdsList = new ArrayList<>(); - String sql2 = "SELECT id FROM `account` WHERE jiqiren=9998"; - ITArray robotId2 = null; - try { - robotId2 = DataBase.use().executeQueryByTArray(sql2); - } catch (SQLException e) { - e.printStackTrace(); - } - for (int j = 0; j < Objects.requireNonNull(robotId2).size(); j++) { - robotIdsList.add(robotId2.getTObject(j).getInt("id")); - } - - - for (String roomId : roomIds) { - String roomId1 = roomId.substring(roomId.indexOf(":") + 1); - roomKey = "room:" + roomId1; - - if (jedis22.hget(roomKey, "players") != null) { - String players = jedis22.hget(roomKey, "players"); - if (!players.equals("[]")) { - players = players.substring(1, players.length() - 1); - playerIds2 = players.split(","); - - - if (playerIds2.length == 1) { - for (String s : playerIds2) { - if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人 - String gpid = jedis22.hget(roomKey, "gpid"); - String gpId = jedis22.hget(roomKey, "group"); - String key = "g{" + gpId + "}:play:" + gpid; - if (!players.equals("[]") && pid == Integer.parseInt(gpid)) { - - - if (JiQiRens.count != null && JiQiRens.count.containsKey(Integer.parseInt(gpid))) { - Integer currentValue = JiQiRens.count.get(Integer.parseInt(gpid)); - if (currentValue > 0) { - JiQiRens.count.put(Integer.parseInt(gpid), currentValue - 1); - } - } - - Jedis jedis20 = Redis.use("group1_db11").getJedis(); - - jedis20.hincrBy(key, "leftover_robot", 1); - jedis20.close(); - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, Integer.parseInt(s)); - - try { - DataBase.use().executeUpdate(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - - client.send("1005", params, response -> { - - }); - - } - } - } - - } - } - } - } - - jedis22.close(); - } else if ("817".equalsIgnoreCase(command)) {//结算 - huNanChangSha.getChangShaCardInhand().clear(); - huNanChangSha.getChuGuoCardInhand().clear(); - huNanChangSha.getpongGroup().clear(); - huNanChangSha.getchowGroup().clear(); - TinHuChi.lastTingCount = 0; - TinHuChi.isMoreThanLast = false; - ChangShaSuanFaTest.isTin=false; - ChangShaSuanFaTest.isChi=false; - ChangShaSuanFaTest.isPeng=false; - ChangShaSuanFaTest.tinCards.clear(); - Integer type = param.getInt("type"); - if (type == 1 || type == 2) { //为1为大结算 为2为解散 - Jedis jedis11s = Redis.use("group1_db11").getJedis(); - try { - String key = "g{" + groupId + "}:play:" + pid; - jedis11s.hincrBy(key, "leftover_robot", 1); -// - if (count != null && count.containsKey(pid)) { - Integer currentValue = count.get(pid); - if (currentValue > 0) { - count.put(pid, currentValue - 1); - } - } - - - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId); - try { - DataBase.use().executeUpdate(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - jedis11s.close(); - } - - if (count != null && count.containsKey(pid)) { - Integer value = count.get(pid); - - // 如果找到了对应的 pid - Jedis jedis12 = Redis.use("group1_db11").getJedis(); - - String shangxianRobot = jedis12.hget(playKey, "shangxian_robot"); - String leftoverRobot = jedis12.hget(playKey, "leftover_robot"); - - if (shangxianRobot != null && leftoverRobot != null) { - if (value == 0) { - jedis12.hset(playKey, "leftover_robot", shangxianRobot); - } - } - jedis12.close(); - } - } -// playerState.pongGroups.clear();; -// playerState.handCards.clear(); -// playerState.chiGroups.clear(); -// playerState.gangGroups.clear();; - - - ready(); - //写定时器 - - } else if ("815".equalsIgnoreCase(command)) { //服务器通知客户端有玩家执行了操作 - //[TCP->815] data:{"playerid":101555,"card":104,"opcard":[105,103],"from_seat":2,"type":1,"opengang":false} - huNanChangSha.shanchuchuguopai(param); - } else if ("820".equalsIgnoreCase(command)) {//换牌提示 - huNanChangSha.changePlayer(command, message); - } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用 -// Jedis jedis11s = Redis.use("group1_db11").getJedis(); -// String key = "g{" + groupId + "}:play:" + pid; -// -// jedis11s.hincrBy(key, "leftover_robot", 1); -// jedis11s.close(); -// try { -// - Set roomIds = scanRooms(jedis0, "room:*"); - String[] playerIds = null; - for (String roomId : roomIds) { - String rid = roomId.substring(roomId.indexOf(":") + 1); - String roomKey = "room:" + rid; - - if (jedis0.hget(roomKey, "players") != null) { - String players = jedis0.hget(roomKey, "players"); - - if (!players.equals("[]")) { - players = players.substring(1, players.length() - 1); - playerIds = players.split(","); - - for (String pyids : playerIds) { - - if (Integer.parseInt(pyids) == playerId) { - jedis0.del(roomId); - } - } - } - } - } - - - } else if ("825".equalsIgnoreCase(command)) { - ITObject params = TObject.newInstance(); - params.putInt("qi", 0); - params.putInt("id", 1); - client.send("612", params, response -> { - - }); - } else if ("822".equalsIgnoreCase(command)) { - ITObject params = TObject.newInstance(); - //params.putInt("qi", 0); - params.putInt("id", 1); - //[TCP->822] data:{"tip_list":[{"type":8,"id":1,"opcard":[],"weight":8,"card":0}],"types":[{"type":21,"value":1}]} - //板胡Event [TCP->823] data:{"type":8,"seat":1,"data":[{"opcard":[204,204,204,108,108,108],"type":21,"value":1}]} - - client.send("612", params, response -> { - - }); - } else if ("835".equalsIgnoreCase(command)) { //听牌天听 - ITObject params = TObject.newInstance(); - params.putInt("qi", 0); - params.putInt("id", 1); - client.send("612", params, response -> { - - }); - - } - - - //END 长沙麻将 - } - } - } - }); - // 添加连接状态监听器 - client.addEventListener(TaurusClient.NetClientEvent.Connect, new - - IEventListener() { - @Override - public void handleEvent(Event event) { - SocketCode code = (SocketCode) event.getParameter("code"); - if (code == SocketCode.Connect) { - - } else { -// - //重连 - -// if ("22".equalsIgnoreCase(wanfaId)) { //湖南红中麻将 -// client = new TaurusClient("8.138.242.190:6421", "game", TaurusClient.ConnectionProtocol.Tcp); -// } -// -// if ("10".equalsIgnoreCase(wanfaId)) { -// client = new TaurusClient("127.0.0.1:6311", "game", TaurusClient.ConnectionProtocol.Tcp); -// } -//// -// if ("66".equalsIgnoreCase(wanfaId)) { -// client = new TaurusClient("8.138.242.190:6841", "game", TaurusClient.ConnectionProtocol.Tcp); -// } -// client.connect(); - - } - } - }); - - - //这里是机器人主动找真人房间进入 - for (String id : roomIds) { - String roomId = id.substring(id.indexOf(":") + 1); - roomKey = "room:" + roomId; - if (jedis0.hget(roomKey, "gpid") != null) { - String gpid = jedis0.hget(roomKey, "gpid"); - String players1 = jedis0.hget(roomKey, "players"); - - if (players1 != null && !players1.equals("[]")) { - - String players = jedis0.hget(roomKey, "players"); - players = players.substring(1, players.length() - 1); - - String[] playerIds1 = players.split(","); - - String sql2 = "SELECT id FROM `account` WHERE jiqiren=9998"; - ITArray robotId2 = DataBase.use().executeQueryByTArray(sql2); - - String maxPlayers = jedis0.hget(roomKey, "maxPlayers"); - if (Integer.parseInt(maxPlayers) == 2) { - if (playerIds1.length == 1) { - //循环playerIds - for (int i = 0; i < playerIds1.length; i++) { - String playeid = playerIds1[i]; - List robotIdsList = new ArrayList<>(); - - for (int j = 0; j < robotId2.size(); j++) { - robotIdsList.add(robotId2.getTObject(j).getInt("id")); - } - - roomKey = "room:" + roomId; - String gpid2 = jedis0.hget(roomKey, "gpid"); - String playKey2 = "g{" + groupId + "}:play:" + gpid2; - String leftover_robot1 = jedis11.hget(playKey2, "leftover_robot"); - - if (!robotIdsList.contains(Integer.parseInt(playeid)) && Integer.parseInt(gpid2) == pid && Integer.parseInt(leftover_robot1) > 0) { - ITObject object = null; - AccountBusiness accountBusiness = null; - accountBusiness = new AccountBusiness(); - // 登录获取session跟token - - if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) { - - Set keys1 = jedis0.keys("{user}:" + playerId + "_token"); - if (keys1 == null) { - object = accountBusiness.idPasswordLogin(playerId, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } else { - Set keys = jedis0.smembers("{user}:" + playerId + "_token"); - List keyList = new ArrayList<>(keys); - session = "{user}:" + playerId; - token = keyList.get(0); - - } - } else { - - object = accountBusiness.idPasswordLogin(playerId, password); - ITObject validate = TObject.newInstance(); - validate.putString("token", object.getString("token")); - token = object.getString("token"); - session = accountBusiness.getSession(); - } - - - String readyTime = jedis0.hget(roomKey, "readyTime"); -// long readyTime1 = Long.parseLong(readyTime); - //判断如果readyTime已经过去七秒 - - //判断准备时间,只是要取出准备时间超过七秒的房间 -// if (System.currentTimeMillis() - readyTime1 > 1000) { - String roomKey1 = "room:" + roomId; - String group = jedis0.hget(roomKey1, "group"); - ITObject roomInfos = GroupRoomBusiness.joinRoom(Integer.parseInt(group), roomKey1, session, null); - joinRoom(playerId); //进入房间 - ready(); //准备 - String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 1, playerId); - DataBase.use().executeUpdate(sql); - String playKey1 = "g{" + groupId + "}:play:" + pid; - - //增加使用数量 - Integer key = Integer.valueOf(pid); - - count.put(key, count.getOrDefault(key, 0) + 1); - - jedis11.hincrBy(playKey1, "leftover_robot", -1); -// } - } - - } - } - } - } - } - - } - - -// ready(); //准备 - } - } - - - } catch (Exception e) { - - e.printStackTrace(); - } finally { - - jedis11.close(); - jedis0.close(); - } - - } - - - */ -/** - * 出牌广播协议 812 - * - * @param command 协议号 - * @param message 消息对象 - * @return - *//* - - public String drawCard(String command, Message message) { - if (command.equalsIgnoreCase("812")) { - ITObject param = message.param; - if (param == null) { - return null; - } - card = param.getString("card"); - - } - return null; - } - - */ -/** - * 位置转换协议 820 - * - * @param command 协议号 - * @param message 消息对象 - * @return - *//* - - public static String changePlayer(String command, Message message) { - if (command.equalsIgnoreCase("820")) { - ITObject param = message.param; - if (param == null) { - return null; - } - -// {seat=2} - - } - return null; - } - - */ -/** - * 摸牌协议 819 - * - * @param command 协议号 - * @param message 消息对象 - * @return - *//* - - public static String getCard(String command, Message message) { - if (command.equalsIgnoreCase("819")) { - ITObject param = message.param; - if (param == null) { - return null; - } -// {seat=2, Ishupai=0, isBaoTing=-1, tingcard=0, isgang=0, card=101, left_count=106} - - if (param.getInt("seat") != null && seat == param.getInt("seat")) { - cardInhand.add(param.getInt("card")); -// cardInhand.add(104); - } - } - return null; - } - - */ -/** - * 扣点点 初始化手牌协议 811 - * - * @param command 协议号 - * @param message 消息对象 - * @param wanfaId 玩法ID - * @return - *//* - - public String cardInHead(String command, Message message, String wanfaId) { - if (command.equalsIgnoreCase("811")) { - ITObject param = message.param; - if (param == null) { - return null; - } -// {bank_seat=1, laiziCard=0, laiziCard2=0, laiziCard2Before=0, jing=0, laiziCardBefore=0, card_list=[101, 103, 104, 201, 204, 207, 208, 209, 307, 309, 501, 502, 503]} - ITArray cardList = param.getTArray("card_list"); - for (int i = 0; i < cardList.size(); i++) { - cardInhand.add(cardList.getInt(i)); - } - if (cardInhand.size() > 13) { - outCard(command, message, wanfaId); - - - } - - - } - return null; - } - - */ -/** - * 出牌方法 - * - * @param command 协议号 - * @param message 消息对象 - * @param wanfaId 玩法ID - * @return - *//* - - public String outCard(String command, Message message, String wanfaId) { - - - - - ITObject params = TObject.newInstance(); - params.putString("session", session + "," + token); - params.putInt("card1", 0); - params.putInt("card", cardInhand.get(0)); - cardInhand.remove(0); - - client.send("611", params, response -> { - - }); - return null; - } - - */ -/** - * 处理杠碰胡操作 - * - * @param param 消息参数 - * @return - *//* - - public String actionCard(ITObject param) { - //获取碰杠胡参数 type 和id 后续算法接入,是否能让碰和杠 - ITArray tipList = param.getTArray("tip_list"); - int id = 0; - int type = 0; - int opcard = 0; - ITObject params = TObject.newInstance(); - if (tipList != null && tipList.size() > 0) { - TObject firstTip = (TObject) tipList.get(0).getObject(); - id = firstTip.getInt("id"); - type = firstTip.getInt("type"); - opcard = firstTip.getTArray("opcard").getInt(0); - - - } - //弃 是根据算法选择是否要弃掉 不进行碰杠胡 - //params.putInt("qi", 0); - //params.putInt("id", 0); - - //执行碰牌 - if (type == 2) { - params.putString("session", session + "," + token); - params.putInt("qi", 0); - params.putInt("id", 1); - Util.removeCard(cardInhand, opcard, 2); - -// Global.logger.info("删除碰的牌"); - //执行胡牌 - } else if (type == 6) { - params.putString("session", session + "," + token); - params.putInt("qi", 0); - params.putInt("id", 1); - - //执行吃杠 - } else if (type == 3) { - params.putString("session", session + "," + token); - params.putInt("qi", 0); - params.putInt("id", 1); - Util.removeCard(cardInhand, opcard, 3); - - //执行自杠 - } else if (type == 4) { - params.putString("session", session + "," + token); - params.putInt("qi", 0); - params.putInt("id", 1); - Util.removeCard(cardInhand, opcard, 4); - - // 碰后补杠 - } else if (type == 5) { - params.putString("session", session + "," + token); - params.putInt("qi", 0); - params.putInt("id", 1); - Util.removeCard(cardInhand, opcard, 1); - - } - -// cardInhand.remove(0); -// cardInhand.remove(1); - - - client.send("612", params, response -> { - - }); - return null; - } - - // 优化方案:使用 scan 替代 keys - public Set scanRooms(Jedis jedis, String pattern) { - Set keys = new HashSet<>(); - String cursor = "0"; - ScanParams scanParams = new ScanParams().match(pattern).count(100); - - do { - ScanResult scanResult = jedis.scan(cursor, scanParams); - keys.addAll(scanResult.getResult()); - cursor = String.valueOf(scanResult.getCursor()); - } while (!cursor.equals("0")); - - return keys; - } - - */ -/** - * 处理补杠操作 - * - * @param param 消息参数 - *//* - - public void buGang(ITObject param) { - Integer card = param.getInt("card"); - ITObject params = TObject.newInstance(); - params.putInt("card", card); - client.send("839", params, response -> { - - }); - } - - - */ -/** - * 准备方法 - * - * @return - *//* - - public String ready() { - try { - // 添加1秒延迟 - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } -// cardInhand = new ArrayList(); -// HuNanHongZhong.hongZhongCardInhand(); -// HuNanFangPaoFa.fangPaoFaCardInhand(); - - ITObject params = TObject.newInstance(); - params.putString("session", session + "," + token); - - client.send("1003", params, new ICallback() { - - @Override - public void action(MessageResponse messageResponse) { - - - } - }); - return null; - } - - - */ -/** - * 加入房间方法 - * - * @return - *//* - - public String joinRoom(int playerId) { - try { - // 添加2秒延迟 - Thread.sleep(5000); - - ITObject params = TObject.newInstance(); - params.putString("session", session + "," + token); - - client.send("1002", params, response -> { - ITObject obj = response.messageData.param.getTObject("tableInfo"); - }); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } - - */ -/** - * 线程休眠方法 - * - * @param time 休眠时间(毫秒) - *//* - - public static void sleepTime(int time) { - try { - // 添加延迟 - Thread.sleep(time); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - */ -/** - * 程序入口点 - * - * @param args - * @throws Exception - *//* - -// public static void main(String[] args) throws Exception { -// try { -// PluginService.me().loadConfig(); -// } catch (Exception e1) { -// e1.printStackTrace(); -// } -// -//// NetManager.debug_print = false; -//// NetManager.TIMEOUT_TIME = 10; -//// NetManager.VERSION = 10; -// -// tcp_test(); -// -// -// while (true) { -// NetManager.processEvents(); -// try { -// Thread.sleep(8); -// } catch (InterruptedException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } -// } -} -*/ diff --git a/robots/majiang/robot_mj_cs/src/main/java/robot/mj/RobotConnectionManager.java b/robots/majiang/robot_mj_cs/src/main/java/robot/mj/RobotConnectionManager.java index ea31504..764e40e 100644 --- a/robots/majiang/robot_mj_cs/src/main/java/robot/mj/RobotConnectionManager.java +++ b/robots/majiang/robot_mj_cs/src/main/java/robot/mj/RobotConnectionManager.java @@ -44,6 +44,8 @@ public class RobotConnectionManager { private final Map lastActivityTime = new ConcurrentHashMap<>();//记录最后活动时间 private final Map> connectionWatchers = new ConcurrentHashMap<>();//连接监视器 private final Map lastDisconnectTime = new ConcurrentHashMap<>();//记录最后断开时间 + private final Map connectEventListeners = new ConcurrentHashMap<>();//连接事件监听器 + private final Map messageEventListeners = new ConcurrentHashMap<>();//消息事件监听器 private final int MAX_RECONNECT_ATTEMPTS = 3;//最大重连次数(减少重试) private final int RECONNECT_DELAY_SECONDS = 5;//重连间隔秒数(增加延迟) private final int CONNECTION_WATCH_INTERVAL = 15;//连接监视间隔秒数(延长检测间隔) @@ -138,6 +140,25 @@ public class RobotConnectionManager { } } + /** + * 移除事件监听器 + */ + private void removeEventListeners(String connecId) { + TaurusClient client = gameClients.get(connecId); + if (client != null) { + IEventListener messageListener = messageEventListeners.remove(connecId); + IEventListener connectListener = connectEventListeners.remove(connecId); + + if (messageListener != null) { + client.removeEventListener(TaurusClient.NetClientEvent.OnEvent, messageListener); + } + if (connectListener != null) { + client.removeEventListener(TaurusClient.NetClientEvent.Connect, connectListener); + } + } + System.out.println("移除事件监听器: {"+connecId+"}"); + } + /** * 停止连接监视器 */ @@ -146,7 +167,7 @@ public class RobotConnectionManager { if (watcher != null && !watcher.isDone()) { watcher.cancel(false); } - System.out.println("停止连接监视器: {"+connecId+"}"); + System.out.println("停止连接监视器定时任务: {"+connecId+"}"); } /** @@ -199,22 +220,32 @@ public class RobotConnectionManager { * 断开与游戏服务器的连接(主动断开) */ public void disconnectFromGameServer(String connecId) { + System.out.println("开始主动断开连接: {"+connecId+"}"); + //主动断开 标记为非活跃连接 activeConnections.put(connecId, false); reconnectAttempts.remove(connecId); lastActivityTime.remove(connecId); + lastDisconnectTime.put(connecId, System.currentTimeMillis()); //停止连接监视器 stopConnectionWatcher(connecId); + //移除事件监听器 + removeEventListeners(connecId); + TaurusClient client = gameClients.remove(connecId); - if (client != null && client.isConnected()) { + if (client != null) { try { - client.killConnection(); - System.out.println("客户端主动断开连接: {"+connecId+"}"); + if (client.isConnected()) { + client.killConnection(); + } + System.out.println("客户端主动断开连接完成: {"+connecId+"}"); } catch (Exception e) { - System.out.println("断开客户端连接时发生异常" + connecId); + System.out.println("断开客户端连接时发生异常: " + connecId + ", 错误: " + e.getMessage()); } + } else { + System.out.println("客户端连接不存在: {"+connecId+"}"); } } @@ -248,6 +279,12 @@ public class RobotConnectionManager { * 安排重连任务 */ private void scheduleReconnect(String connecId) { + //检查是否仍然是活跃连接 + if (!activeConnections.getOrDefault(connecId, false)) { + System.out.println("连接已非活跃,取消重连安排: {"+connecId+"}"); + return; + } + Integer attempts = reconnectAttempts.getOrDefault(connecId, 0); //最大重连次数 if (attempts >= 5) { @@ -257,16 +294,19 @@ public class RobotConnectionManager { } reconnectAttempts.put(connecId, attempts + 1); - System.out.println("安排重连任务: {"+connecId+"}, 第{"+attempts + 1+"}次尝试"); + System.out.println("安排重连任务: {"+connecId+"}, 第{"+(attempts + 1)+"}次尝试"); reconnectScheduler.schedule(() -> { try { + //再次检查连接状态 if (activeConnections.getOrDefault(connecId, false)) { System.out.println("开始重连: {"+connecId+"}"); reconnectToGameServer(connecId); + } else { + System.out.println("重连前检查发现连接已非活跃,取消重连: {"+connecId+"}"); } } catch (Exception e) { - System.out.println("重连失败: {"+connecId+"}"); + System.out.println("重连失败: {"+connecId+"}, 错误: " + e.getMessage()); } }, 1, TimeUnit.SECONDS);//重连间隔秒 } @@ -275,6 +315,12 @@ public class RobotConnectionManager { * 重新连接到游戏服务器 */ private void reconnectToGameServer(String connecId) { + //检查是否仍然是活跃连接 + if (!activeConnections.getOrDefault(connecId, false)) { + System.out.println("连接已标记为非活跃,取消重连: {"+connecId+"}"); + return; + } + try { //检查是否已经有连接 TaurusClient existingClient = gameClients.get(connecId); @@ -284,7 +330,7 @@ public class RobotConnectionManager { return; } - //移除旧的客户端 + //移除旧的客户端和事件监听器 if (existingClient != null) { try { existingClient.killConnection(); @@ -293,11 +339,13 @@ public class RobotConnectionManager { } gameClients.remove(connecId); } + //清理旧的事件监听器 + removeEventListeners(connecId); //创建新连接 TaurusClient client = new TaurusClient(host + ":" + port, "game", TaurusClient.ConnectionProtocol.Tcp); - //事件监听器 + //设置新的事件监听器 setupEventListeners(client, connecId); client.connect(); @@ -311,8 +359,10 @@ public class RobotConnectionManager { startConnectionWatcher(connecId); } catch (Exception e) { log.error("重连过程中发生异常: " + connecId, e); - //继续安排下次重连 - scheduleReconnect(connecId); + //检查是否仍然是活跃连接后再安排下次重连 + if (activeConnections.getOrDefault(connecId, false)) { + scheduleReconnect(connecId); + } } } @@ -320,10 +370,19 @@ public class RobotConnectionManager { * 设置事件监听器 */ private void setupEventListeners(TaurusClient client, String connecId) { - // 添加事件监听器处理网络消息 - client.addEventListener(TaurusClient.NetClientEvent.OnEvent, new IEventListener() { + // 先移除可能存在的旧监听器 + removeEventListeners(connecId); + + // 添加消息事件监听器 + IEventListener messageListener = new IEventListener() { @Override public void handleEvent(Event event) { + //检查连接是否仍然有效 + if (!activeConnections.getOrDefault(connecId, false)) { + System.out.println("消息监听器: 连接已非活跃,忽略消息: {"+connecId+"}"); + return; + } + //获取 msg Message message = (Message) event.getParameter("msg"); @@ -341,14 +400,21 @@ public class RobotConnectionManager { handleProtocol(command, message, client, connecId); } } - }); + }; //添加连接状态监听器 - client.addEventListener(TaurusClient.NetClientEvent.Connect, new IEventListener() { + IEventListener connectListener = new IEventListener() { @Override public void handleEvent(Event event) { + //检查连接是否仍然应该处理事件 + if (!activeConnections.getOrDefault(connecId, false)) { + System.out.println("连接监听器: 连接已标记为非活跃,忽略状态变更: {"+connecId+"}"); + return; + } + Message message = (Message) event.getParameter("msg"); SocketCode code = (SocketCode) event.getParameter("code"); + if (code == SocketCode.Connect) { System.out.println("csmj Connect connecId: " + connecId); //连接成功 标记为活跃连接并重置重连次数 @@ -371,7 +437,15 @@ public class RobotConnectionManager { } } } - }); + }; + + //注册事件监听器 + client.addEventListener(TaurusClient.NetClientEvent.OnEvent, messageListener); + client.addEventListener(TaurusClient.NetClientEvent.Connect, connectListener); + + //保存监听器引用以便后续移除 + messageEventListeners.put(connecId, messageListener); + connectEventListeners.put(connecId, connectListener); } /** @@ -635,6 +709,7 @@ public class RobotConnectionManager { EXGameController.removeRobotRoomInfo(String.valueOf(robotId)); //更新机器人剩余数量 updateLeftoverRobot(gpId, gpid, robotId); + disconnectFromGameServer(connecId); jedis0.del(roomKey); System.out.println("2008结束房间,robotId: {"+robotId+"}"); } @@ -832,4 +907,49 @@ public class RobotConnectionManager { return gameClients.get(connecId); } + /** + * 清理所有连接和资源 + */ + public void cleanupAllConnections() { + System.out.println("开始清理所有连接和资源..."); + + //标记所有连接为非活跃 + for (String connecId : activeConnections.keySet()) { + activeConnections.put(connecId, false); + } + + //断开所有连接 + for (String connecId : new ArrayList<>(gameClients.keySet())) { + disconnectFromGameServer(connecId); + } + + //停止所有监视器 + for (String connecId : new ArrayList<>(connectionWatchers.keySet())) { + stopConnectionWatcher(connecId); + } + + //关闭调度器 + reconnectScheduler.shutdown(); + try { + if (!reconnectScheduler.awaitTermination(5, TimeUnit.SECONDS)) { + reconnectScheduler.shutdownNow(); + } + } catch (InterruptedException e) { + reconnectScheduler.shutdownNow(); + Thread.currentThread().interrupt(); + } + + //清理所有缓存数据 + activeConnections.clear(); + reconnectAttempts.clear(); + lastActivityTime.clear(); + lastDisconnectTime.clear(); + connectionWatchers.clear(); + connectEventListeners.clear(); + messageEventListeners.clear(); + gameClients.clear(); + + System.out.println("所有连接和资源清理完成"); + } + } \ No newline at end of file