package taurus.newRobot; 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.StringUtil; import hunan.*; import redis.clients.jedis.*; 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.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static hunan.JiQiRens.sleepTime; public class AddRoomRobot { public String wanfaId = ""; // 会话标识 private String session = ""; // 访问令牌 public String token = ""; // 客户端连接对象 private static 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 Map> playerOutcardsMap = new HashMap<>(); private Map> playerchisMap = new HashMap<>(); private Map> playerpengsMap = new HashMap<>(); private Map> playermingsMap = new HashMap<>(); private Map> playerzisMap = new HashMap<>(); private Map mapclient = new HashMap<>(); public void addRoom() { Jedis jedis2 = Redis.use("group1_db2").getJedis(); Jedis jedis11 = Redis.use("group1_db11").getJedis(); Jedis jedis0 = Redis.use().getJedis(); //获取圈子id和玩法id List gKeys = scanKeysByPattern(jedis2, "g{*}:play:*"); try { if (jedis11.keys("group:*") != null) { Set groupIds = jedis11.keys("group:*"); for (String group : groupIds) { String groupId = group.substring(group.indexOf(":") + 1); String groupKey = "g{" + groupId + "}:play:*"; if (jedis11.keys(groupKey) != null) { Set playIds = jedis11.keys(groupKey); // 遍历圈子下面的玩法 for (String pid : playIds) { String playId = pid.substring(pid.indexOf("play:") + 5); String playKey = "g{" + groupId + "}:play:" + playId; String leftover_robot = "0"; if (jedis11.hget(playKey, "leftover_robot") != null) { leftover_robot = jedis11.hget(playKey, "leftover_robot"); if (Integer.parseInt(leftover_robot) > 0) { //给圈子玩法分配机器人,创建到redis addPlayRobot(groupId, playId, leftover_robot); } } } } } } Map> stringListMap = analyzePlayStructure(gKeys); //取出 圈子玩法里的 机器人使用所有的状态 Map>> playDetails = getPlayDetails(jedis2, stringListMap); System.out.println("result" + playDetails); //统计 玩法里 等待中的次数 为1的有几个 ,然后需要建立几个房间 Map> stringMapMap = analyzeAndMarkRoomsWithCircle(playDetails); System.out.println("stringIntegerMap" + stringMapMap); Map>> allCreatedRooms = new HashMap<>(); // 按圈子ID排序处理 List circleIds = new ArrayList<>(stringMapMap.keySet()); Collections.sort(circleIds); for (String circleId : circleIds) { Map playRoomMap = stringMapMap.get(circleId); System.out.println("\n=== 处理圈子 " + circleId + " ==="); // 为当前圈子创建房间 Map> createdRooms = createRoomsForCircle(circleId, playRoomMap); allCreatedRooms.put(circleId, createdRooms); } // Object room = GroupRoomBusiness.matchRoom(groupId, pid, session, "Android", false); // try { // String game = jedis0.hget(String.valueOf(room), "game"); // wanfaId = String.valueOf(game); // }catch (Exception e){ // e.printStackTrace(); // }finally { // jedis0.close(); // } // System.out.println("chaungjianwanfa" + gKeys); } catch (Exception e) { e.printStackTrace(); } finally { jedis2.close(); jedis11.close(); } } /** * 为单个圈子创建房间 */ public Map> createRoomsForCircle(String circleId, Map playRoomMap) { Map> createdRooms = new HashMap<>(); Jedis jedis2 = Redis.use("group1_db2").getJedis(); Jedis jedis11 = Redis.use("group1_db11").getJedis(); Jedis jedis0 = Redis.use().getJedis(); // 按玩法ID排序处理 List> sortedPlays = playRoomMap.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toList()); for (Map.Entry entry : sortedPlays) { String playId = entry.getKey(); int requiredRooms = entry.getValue(); if (requiredRooms <= 0) { System.out.println("玩法 " + playId + ": 跳过创建 (需求数=" + requiredRooms + ")"); continue; } System.out.println("玩法 " + playId + ": 创建 " + requiredRooms + " 个房间"); List roomsForPlay = new ArrayList<>(); for (int i = 1; i <= requiredRooms; i++) { try { String keys = "g{" + circleId + "}:play:" + playId; Map stringStringMap = jedis2.hgetAll(keys); List zeroValueKeys = getKeysWithValueZero(stringStringMap); System.out.println("值为0的机器人ID: " + zeroValueKeys); String randomKeyFromList = getRandomKeyFromList(zeroValueKeys); System.out.println("随机给的用户id----" + randomKeyFromList); jedis2.hset(keys, randomKeyFromList, "1"); ITObject object = null; AccountBusiness accountBusiness = null; accountBusiness = new AccountBusiness(); // 登录获取session跟token if (jedis0.keys("{user}:" + randomKeyFromList + "_token").size() != 0) { Set keys1 = jedis0.keys("{user}:" + randomKeyFromList + "_token"); if (keys1 == null) { object = accountBusiness.idPasswordLogin(Integer.parseInt(randomKeyFromList), "123456"); ITObject validate = TObject.newInstance(); validate.putString("token", object.getString("token")); token = object.getString("token"); session = accountBusiness.getSession(); } else { Set keys2 = jedis0.smembers("{user}:" + randomKeyFromList + "_token"); List keyList = new ArrayList<>(keys2); session = "{user}:" + randomKeyFromList; token = keyList.get(0); } } else { object = accountBusiness.idPasswordLogin(Integer.parseInt(randomKeyFromList), "123456"); ITObject validate = TObject.newInstance(); validate.putString("token", object.getString("token")); token = object.getString("token"); session = accountBusiness.getSession(); } // 调用原有的房间匹配逻辑 Object room = GroupRoomBusiness.matchRoom(Integer.parseInt(circleId), Integer.parseInt(playId), session, "Android", false); String game = jedis0.hget(String.valueOf(room), "game"); wanfaId = String.valueOf(game); String roomKey = String.valueOf(room); System.out.println("roomkey--------" + roomKey); client = null; System.out.println("wanfaId" + wanfaId); // List circleIds = new ArrayList<>(); if ("22".equalsIgnoreCase(wanfaId)) { //湖南红中麻将 client = new TaurusClient("8.138.242.190:6421", "game", TaurusClient.ConnectionProtocol.Tcp); } if ("10".equalsIgnoreCase(wanfaId)) { client = new TaurusClient("8.138.242.190:6311", "game", TaurusClient.ConnectionProtocol.Tcp); client.connect(); mapclient.put(randomKeyFromList,client); } // if ("66".equalsIgnoreCase(wanfaId)) { client = new TaurusClient("8.138.242.190:6841", "game", TaurusClient.ConnectionProtocol.Tcp); } System.out.println("mapclient----"+mapclient); ITObject roomInfos = GroupRoomBusiness.joinRoom(Integer.parseInt(circleId), roomKey, this.session, null); String roomId = roomInfos.getString("room_id"); String robort = "{robortInfo}:" + randomKeyFromList; jedis2.hset(robort, "room_id", roomId); jedis2.hset(robort, "circleId", circleId); jedis2.hset(robort, "pid", playId); joinRoom(Integer.parseInt(randomKeyFromList)); //进入房间 ready(); //准备 String playKey1 = "g{" + circleId + "}:play:" + playId; jedis11.hincrBy(playKey1, "leftover_robot", -1); if (room != null) { roomsForPlay.add(room); System.out.println(" 第 " + i + " 个房间创建成功"); } else { System.out.println(" 第 " + i + " 个房间创建失败"); } // // 控制创建间隔 // if (i < requiredRooms) { // Thread.sleep(100); // } // // 添加事件监听器处理网络消息 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 ("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)) { //长沙麻将 机器人处理事件 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)) { //db0 Jedis jedis22 = Redis.use().getJedis(); //db2 Jedis jedis33 = Redis.use("group1_db2").getJedis(); sleepTime(5000); System.out.println("param ++++++++++++++++ " + param); Integer aid = param.getInt("aid"); ITObject params = TObject.newInstance(); String getKey ="{robortInfo}:"+aid; String circleId1 = jedis33.hget(getKey, "circleId"); String pid = jedis33.hget(getKey, "pid"); if (!pid.equals("0")){ String key = "g{" + circleId1 + "}:play:" + pid; Jedis jedis20 = Redis.use("group1_db11").getJedis(); System.out.println("进入 -------------------------"); jedis20.hincrBy(key, "leftover_robot", 1); jedis20.close(); System.out.println("client ++++= " + client); for (Map.Entry entry : mapclient.entrySet()) { String key1 = entry.getKey(); if (Integer.parseInt(key1)==aid){ Object value = entry.getValue(); TaurusClient client1 = (TaurusClient) value; client1.send("1005", params, response -> { }); } } sleepTime(1000); jedis33.hset(getKey, "circleId","0"); jedis33.hset(getKey, "pid","0"); jedis33.hset(getKey, "room_id","0"); } jedis33.close(); 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 { } } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.err.println("创建过程被中断"); break; } catch (Exception e) { System.err.println("创建房间时出错: " + e.getMessage()); } } createdRooms.put(playId, roomsForPlay); jedis2.close(); jedis11.close(); jedis0.close(); } return createdRooms; } /** * 线程休眠方法 * * @param time 休眠时间(毫秒) */ public static void sleepTime(int time) { try { // 添加延迟 Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 加入房间方法 * * @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; } /** * 准备方法 * * @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; } //统计 玩法里 等待中的次数 // 方法1:返回 Map<圈子ID, Map<玩法ID, 房间需求>> public Map> analyzeAndMarkRoomsWithCircle( Map>> result) { Map> circlePlayRoomMap = new HashMap<>(); for (Map.Entry>> circleEntry : result.entrySet()) { String circleId = circleEntry.getKey(); Map> playData = circleEntry.getValue(); Map playRoomMark = new HashMap<>(); for (Map.Entry> playEntry : playData.entrySet()) { String playId = playEntry.getKey(); Map robotData = playEntry.getValue(); // 统计值为"1"的机器人数量 int countOfOnes = 0; for (String value : robotData.values()) { if ("1".equals(value)) { countOfOnes++; } } // 根据逻辑进行标记 if (countOfOnes == 0) { playRoomMark.put(playId, 2); // 需要建立2个房间 } else if (countOfOnes == 1) { playRoomMark.put(playId, 1); // 标记为1 } else if (countOfOnes >= 2) { playRoomMark.put(playId, 0); // 标记为0 } } circlePlayRoomMap.put(circleId, playRoomMark); } return circlePlayRoomMap; } //获取为0的value public static List getKeysWithValueZero(Map robotData) { List result = new ArrayList<>(); for (Map.Entry entry : robotData.entrySet()) { if ("0".equals(entry.getValue())) { result.add(entry.getKey()); } } return result; } //随机分配机器人 public String getRandomKeyFromList(List zeroValueKeys) { if (zeroValueKeys == null || zeroValueKeys.isEmpty()) { return null; } Random random = new Random(); int randomIndex = random.nextInt(zeroValueKeys.size()); return zeroValueKeys.get(randomIndex); } // 统计每个玩法的机器人总数 public Map>> getPlayDetails(Jedis jedis, Map> circleToPlays) { Map>> result = new HashMap<>(); for (Map.Entry> entry : circleToPlays.entrySet()) { String circleId = entry.getKey(); List playIds = entry.getValue(); Map> playDetails = new HashMap<>(); for (String playId : playIds) { // 构建Redis键 String redisKey = String.format("g{%s}:play:%s", circleId, playId); // 获取Hash中的所有字段和值 Map robotData = jedis.hgetAll(redisKey); playDetails.put(playId, robotData); } result.put(circleId, playDetails); } return result; } //分割圈子和玩法 public static Map> analyzePlayStructure(List gKeys) { Map> circleToPlays = new HashMap<>(); for (String key : gKeys) { // 解析键:g{圈子ID}:play:玩法ID String[] parts = key.split(":"); if (parts.length >= 3) { // 提取圈子ID,去掉 g{ 和 } String circlePart = parts[0]; // g{330800} String circleId = circlePart.substring(2, circlePart.length() - 1); // 提取玩法ID String playId = parts[2]; // 玩法ID // 将玩法ID添加到对应圈子的列表中 circleToPlays.computeIfAbsent(circleId, k -> new ArrayList<>()) .add(playId); } } return circleToPlays; } /** * 使用SCAN命令安全地扫描匹配模式的key */ private static List scanKeysByPattern(Jedis jedis, String pattern) { List keys = new ArrayList<>(); String cursor = ScanParams.SCAN_POINTER_START; ScanParams scanParams = new ScanParams(); scanParams.match(pattern); scanParams.count(1000); // 每次扫描数量 do { ScanResult scanResult = jedis.scan(cursor, scanParams); cursor = String.valueOf(scanResult.getCursor()); keys.addAll(scanResult.getResult()); } while (!cursor.equals(ScanParams.SCAN_POINTER_START)); return keys; } //给圈子玩法分配机器人,创建到redis public void addPlayRobot(String groupId, String playId, String leftover_robot) { Jedis jedis2 = Redis.use("group1_db2").getJedis(); // 为这个玩法创建机器人配置 String robotPlayKey = "g{" + groupId + "}:play:" + playId; boolean exists = jedis2.exists(robotPlayKey); if (!exists) { // 计算需要配置的机器人数量 int num = Integer.parseInt(leftover_robot) * 2; // 获取所有可用的机器人 List availableRobots1 = getAvailableRobots(); List availableRobots = new ArrayList<>(); if (availableRobots1.size() > 0) { for (String key : availableRobots1) { String robotId = key.substring(key.indexOf(":") + 1); availableRobots.add(robotId); } // 检查是否有足够的机器人 if (availableRobots.size() < num) { System.out.println("警告:玩法 " + playId + " 需要 " + num + " 个机器人,但只有 " + availableRobots.size() + " 个可用"); return; } } // 存储机器人信息,使用Hash结构 Map robotConfigs = new HashMap<>(); for (int i = 0; i < num; i++) { String robotId = availableRobots.get(i); // key格式:robot:机器人ID,value:使用状态(0-未使用) robotConfigs.put(robotId, "0"); String robotKey = "{robot}:" + robotId; jedis2.hset(robotKey, "start", "1"); } // 批量设置机器人配置 if (!robotConfigs.isEmpty()) { jedis2.hmset(robotPlayKey, robotConfigs); System.out.println("玩法 " + playId + " 已配置 " + num + " 个机器人"); } jedis2.close(); } } /** * 获取所有可用的机器人(start=0) * * @return 可用机器人ID列表 */ public List getAvailableRobots() { Jedis jedis2 = Redis.use("group1_db2").getJedis(); Set allRobotKeys = jedis2.keys("{robot}:*"); List availableRobots = new ArrayList<>(); // 使用Pipeline提高效率 Pipeline pipeline = jedis2.pipelined(); List> responses = new ArrayList<>(); for (String robotKey : allRobotKeys) { responses.add(pipeline.hget(robotKey, "start")); } pipeline.sync(); // 提取机器人ID并筛选 int index = 0; for (String robotKey : allRobotKeys) { String startStatus = responses.get(index).get(); if ("0".equals(startStatus)) { String robotId = robotKey.substring(robotKey.indexOf(":") + 1); availableRobots.add(robotId); } index++; } jedis2.close(); return availableRobots; } }