proj_name
stringclasses
26 values
relative_path
stringlengths
42
188
class_name
stringlengths
2
53
func_name
stringlengths
2
49
masked_class
stringlengths
68
178k
func_body
stringlengths
56
6.8k
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/proxy/ProtobufProxy.java
ProtobufProxy
connect
class ProtobufProxy implements Proxy { @Override public void connect(String serverAddress, int port) throws InterruptedException {<FILL_FUNCTION_BODY>} }
EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS)) .addLast(new ProtobufVarint32FrameDecoder()) .addLast(new ProtobufDecoder(ClientTransferData.ClientTransferDataProtoc.getDefaultInstance())) .addLast(new ProtobufVarint32LengthFieldPrepender()) .addLast(new ProtobufEncoder()) .addLast(new SecondProtobufCodec()) .addLast(new ProtobufTransferHandler()); } }); SimplePrinter.printNotice("Connecting to " + serverAddress + ":" + port); Channel channel = bootstrap.connect(serverAddress, port).sync().channel(); channel.closeFuture().sync(); } finally { group.shutdownGracefully().sync(); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/proxy/WebsocketProxy.java
WebsocketProxy
initChannel
class WebsocketProxy implements Proxy{ @Override public void connect(String serverAddress, int port) throws InterruptedException, URISyntaxException { URI uri = new URI("ws://" + serverAddress + ":" + port + "/ratel"); EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception {<FILL_FUNCTION_BODY>} }); SimplePrinter.printNotice("Connecting to " + serverAddress + ":" + port); Channel channel = bootstrap.connect(serverAddress, port).sync().channel(); channel.closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } }
ch.pipeline() .addLast(new IdleStateHandler(60 * 30, 0, 0, TimeUnit.SECONDS)) .addLast(new HttpClientCodec()) .addLast(new HttpObjectAggregator(8192)) .addLast(new WebSocketClientProtocolHandler(uri , WebSocketVersion.V13 , null , true , new DefaultHttpHeaders(), 100000)) .addLast("ws", new WebsocketTransferHandler());
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/channel/ChannelUtils.java
ChannelUtils
pushToClient
class ChannelUtils { public static void pushToClient(Channel channel, ClientEventCode code, String data) { pushToClient(channel, code, data, null); } public static void pushToClient(Channel channel, ClientEventCode code, String data, String info) {<FILL_FUNCTION_BODY>} public static ChannelFuture pushToServer(Channel channel, ServerEventCode code, String data) { if (channel.pipeline().get("ws") != null) { Msg msg = new Msg(); msg.setCode(code.toString()); msg.setData(data); return channel.writeAndFlush(new TextWebSocketFrame(JsonUtils.toJson(msg))); } else { ServerTransferData.ServerTransferDataProtoc.Builder serverTransferData = ServerTransferData.ServerTransferDataProtoc.newBuilder(); if (code != null) { serverTransferData.setCode(code.toString()); } if (data != null) { serverTransferData.setData(data); } return channel.writeAndFlush(serverTransferData); } } }
if (channel != null) { if (channel.pipeline().get("ws") != null) { Msg msg = new Msg(); msg.setCode(code.toString()); msg.setData(data); msg.setInfo(info); channel.writeAndFlush(new TextWebSocketFrame(JsonUtils.toJson(msg))); } else { ClientTransferData.ClientTransferDataProtoc.Builder clientTransferData = ClientTransferData.ClientTransferDataProtoc.newBuilder(); if (code != null) { clientTransferData.setCode(code.toString()); } if (data != null) { clientTransferData.setData(data); } if (info != null) { clientTransferData.setInfo(info); } channel.writeAndFlush(clientTransferData); } }
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/entity/ClientSide.java
ClientSide
equals
class ClientSide { private int id; private int roomId; private int score; private int scoreInc; private int round; private String nickname; private List<Poker> pokers; private ClientStatus status; private ClientRole role; private ClientType type; private ClientSide next; private ClientSide pre; private transient Channel channel; private String version; public ClientSide() {} public ClientSide(int id, ClientStatus status, Channel channel) { this.id = id; this.status = status; this.channel = channel; } public void init() { roomId = 0; pokers = null; status = ClientStatus.TO_CHOOSE; type = null; next = null; pre = null; score = 0; } public final void resetRound() { round = 0; } public final int getRound() { return round; } public final void addRound() { round += 1; } public final ClientRole getRole() { return role; } public final void setRole(ClientRole role) { this.role = role; } public final String getNickname() { return nickname; } public final void setNickname(String nickname) { this.nickname = nickname; } public final Channel getChannel() { return channel; } public final void setChannel(Channel channel) { this.channel = channel; } public final int getRoomId() { return roomId; } public final void setRoomId(int roomId) { this.roomId = roomId; } public final List<Poker> getPokers() { return pokers; } public final void setPokers(List<Poker> pokers) { this.pokers = pokers; } public final int getScore() { return score; } public final void setScore(int score) { this.score = score; } public final void addScore(int score) { this.score += score; this.scoreInc = score; } public final void setScoreInc(int scoreInc) { this.scoreInc = scoreInc; } public final int getScoreInc() { return this.scoreInc; } public final ClientStatus getStatus() { return status; } public final void setStatus(ClientStatus status) { this.status = status; } public final ClientType getType() { return type; } public final void setType(ClientType type) { this.type = type; } public final int getId() { return id; } public final void setId(int id) { this.id = id; } public final ClientSide getNext() { return next; } public final void setNext(ClientSide next) { this.next = next; } public final ClientSide getPre() { return pre; } public final void setPre(ClientSide pre) { this.pre = pre; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} }
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ClientSide other = (ClientSide) obj; return id == other.id;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/entity/Poker.java
Poker
equals
class Poker { private PokerLevel level; private PokerType type; public Poker() { } public Poker(PokerLevel level, PokerType type) { this.level = level; this.type = type; } public final PokerLevel getLevel() { return level; } public final void setLevel(PokerLevel level) { this.level = level; } public final PokerType getType() { return type; } public final void setType(PokerType type) { this.type = type; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((level == null) ? 0 : level.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public String toString() { return level.getLevel() + " "; } }
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Poker other = (Poker) obj; if (level != other.level) return false; return type == other.type;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/entity/PokerSell.java
PokerSell
toString
class PokerSell { private int score; private SellType sellType; private List<Poker> sellPokers; private int coreLevel; public PokerSell(SellType sellType, List<Poker> sellPokers, int coreLevel) { this.score = PokerHelper.parseScore(sellType, coreLevel); this.sellType = sellType; this.sellPokers = sellPokers; this.coreLevel = coreLevel; } public final int getCoreLevel() { return coreLevel; } public final void setCoreLevel(int coreLevel) { this.coreLevel = coreLevel; } public final int getScore() { return score; } public final void setScore(int score) { this.score = score; } public final SellType getSellType() { return sellType; } public final void setSellType(SellType sellType) { this.sellType = sellType; } public final List<Poker> getSellPokers() { return sellPokers; } public final void setSellPokers(List<Poker> sellPokers) { this.sellPokers = sellPokers; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return sellType + "\t| " + score + "\t|" + sellPokers;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/features/Features.java
Features
supported
class Features { public final static String VERSION_1_3_0 = "v1.3.0"; public final static String READY = "READY"; private final static Map<String, List<String>> FEATURES = new HashMap<>(); static{ FEATURES.put(VERSION_1_3_0, Collections.singletonList(READY)); } public static boolean supported(String clientVersion, String feature){<FILL_FUNCTION_BODY>} }
List<String> features = FEATURES.get(clientVersion); if (Objects.isNull(features) || Objects.isNull(feature)){ return false; } return features.contains(feature.toUpperCase(Locale.ROOT));
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/handler/DefaultDecoder.java
DefaultDecoder
decode
class DefaultDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {<FILL_FUNCTION_BODY>} }
int startIndex; int endIndex; if ((startIndex = in.indexOf(in.readerIndex(), in.writerIndex(), TransferProtocolUtils.PROTOCOL_HAED)) != -1 && (endIndex = in.indexOf(startIndex + 1, in.writerIndex(), TransferProtocolUtils.PROTOCOL_TAIL)) != -1) { endIndex++; byte[] bytes = new byte[endIndex - startIndex]; in.skipBytes(startIndex - in.readerIndex()); in.readBytes(bytes, 0, bytes.length); out.add(bytes); }
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/helper/TimeHelper.java
TimeHelper
sleep
class TimeHelper { public static void sleep(long millis) {<FILL_FUNCTION_BODY>} }
try { Thread.sleep(millis); } catch (InterruptedException ignored) { }
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/print/SimplePrinter.java
SimplePrinter
printNotice
class SimplePrinter { private final static SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static int pokerDisplayFormat = 0; public static void printPokers(List<Poker> pokers) { System.out.println(PokerHelper.printPoker(pokers)); } public static void printNotice(String msg) { System.out.println(msg); } public static void printNotice(String msgKey, String locale) {<FILL_FUNCTION_BODY>} public static void serverLog(String msg) { System.out.println(FORMAT.format(new Date()) + "-> " + msg); } }
//TODO : read locale Map<String, Map<String, String>> map = new HashMap<>(); map.put("english", new HashMap<>()); map.get("eng").put("caterpillar", "caterpillar's message!!"); System.out.println(map.get(locale).get(msgKey));
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/print/SimpleWriter.java
SimpleWriter
write
class SimpleWriter { private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static String write(String message) { return write("player", message); } public static String write(String nickname, String message) {<FILL_FUNCTION_BODY>} public static String write() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } }
System.out.println(); System.out.printf("[%s@%s]$ ", nickname, message); try { return write(); } finally { System.out.println(); }
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/robot/EasyRobotDecisionMakers.java
EasyRobotDecisionMakers
howToPlayPokers
class EasyRobotDecisionMakers extends AbstractRobotDecisionMakers { private static Random random = new Random(); @Override public PokerSell howToPlayPokers(PokerSell lastPokerSell, ClientSide robot) {<FILL_FUNCTION_BODY>} @Override public int getLandlordScore(List<Poker> leftPokers, List<Poker> rightPokers, List<Poker> myPokers) { List<PokerSell> leftSells = PokerHelper.parsePokerSells(leftPokers); List<PokerSell> mySells = PokerHelper.parsePokerSells(myPokers); List<PokerSell> rightSells = PokerHelper.parsePokerSells(rightPokers); int expectedScore = 0; if (mySells.size() > leftSells.size()) { ++expectedScore; } if (mySells.size() > rightSells.size()) { ++expectedScore; } if (expectedScore != 0) { ++expectedScore; } return expectedScore; } }
if (lastPokerSell != null && lastPokerSell.getSellType() == SellType.KING_BOMB) { return null; } List<PokerSell> sells = PokerHelper.parsePokerSells(robot.getPokers()); if (lastPokerSell == null) { return sells.get(random.nextInt(sells.size())); } for (PokerSell sell : sells) { if (sell.getSellType() == lastPokerSell.getSellType()) { if (sell.getScore() > lastPokerSell.getScore() && sell.getSellPokers().size() == lastPokerSell.getSellPokers().size()) { return sell; } } } if (lastPokerSell.getSellType() != SellType.BOMB) { for (PokerSell sell : sells) { if (sell.getSellType() == SellType.BOMB) { return sell; } } } for (PokerSell sell : sells) { if (sell.getSellType() == SellType.KING_BOMB) { return sell; } } return null;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/robot/MediumRobotDecisionMakers.java
MediumRobotDecisionMakers
deduce
class MediumRobotDecisionMakers extends AbstractRobotDecisionMakers { private static final Long DEDUCE_LIMIT = 100 * 3L; public MediumRobotDecisionMakers() {} @Override public PokerSell howToPlayPokers(PokerSell lastPokerSell, ClientSide robot) { if(lastPokerSell != null && lastPokerSell.getSellType() == SellType.KING_BOMB) { return null; } List<Poker> selfPoker = PokerHelper.clonePokers(robot.getPokers()); List<Poker> leftPoker = PokerHelper.clonePokers(robot.getPre().getPokers()); List<Poker> rightPoker = PokerHelper.clonePokers(robot.getNext().getPokers()); PokerHelper.sortPoker(selfPoker); PokerHelper.sortPoker(leftPoker); PokerHelper.sortPoker(rightPoker); List<List<Poker>> pokersList = new ArrayList<List<Poker>>(); pokersList.add(selfPoker); pokersList.add(rightPoker); pokersList.add(leftPoker); List<PokerSell> sells = PokerHelper.validSells(lastPokerSell, selfPoker); if(sells.size() == 0) { return null; } PokerSell bestSell = null; Long weight = null; for(PokerSell sell: sells) { List<Poker> pokers = PokerHelper.clonePokers(selfPoker); pokers.removeAll(sell.getSellPokers()); if(pokers.size() == 0) { return sell; } pokersList.set(0, pokers); AtomicLong counter = new AtomicLong(); deduce(0, sell, 1, pokersList, counter); if(weight == null) { bestSell = sell; weight = counter.get(); }else if (counter.get() > weight){ bestSell = sell; weight = counter.get(); } pokersList.set(0, selfPoker); } return bestSell; } private Boolean deduce(int sellCursor, PokerSell lastPokerSell, int cursor, List<List<Poker>> pokersList, AtomicLong counter) {<FILL_FUNCTION_BODY>} private static String serialPokers(List<Poker> pokers){ if(pokers == null || pokers.size() == 0) { return "n"; } StringBuilder builder = new StringBuilder(); for(int index = 0; index < pokers.size(); index ++) { builder.append(pokers.get(index).getLevel().getLevel()).append(index == pokers.size() - 1 ? "" : "_"); } return builder.toString(); } private static String serialPokersList(List<List<Poker>> pokersList){ StringBuilder builder = new StringBuilder(); for(int index = 0; index < pokersList.size(); index ++) { List<Poker> pokers = pokersList.get(index); builder.append(serialPokers(pokers)).append(index == pokersList.size() - 1 ? "" : "m"); } return builder.toString(); } @Override public int getLandlordScore(List<Poker> leftPokers, List<Poker> rightPokers, List<Poker> myPokers) { int leftScore = PokerHelper.parsePokerColligationScore(leftPokers); int rightScore = PokerHelper.parsePokerColligationScore(rightPokers); int myScore = PokerHelper.parsePokerColligationScore(myPokers); int expectedScore = 0; if (myScore >= Math.min(leftScore, rightScore)) { ++expectedScore; } if (myScore * 2 >= leftScore + rightScore) { ++expectedScore; } if (myScore >= Math.max(leftScore, rightScore)) { ++expectedScore; } return expectedScore; } }
if(cursor > 2) { cursor = 0; } if(sellCursor == cursor) { lastPokerSell = null; } List<Poker> original = pokersList.get(cursor); List<PokerSell> sells = PokerHelper.validSells(lastPokerSell, original); if(sells.size() == 0) { if(sellCursor != cursor) { return deduce(sellCursor, lastPokerSell, cursor + 1, pokersList, counter); } } for(PokerSell sell: sells) { List<Poker> pokers = PokerHelper.clonePokers(original); pokers.removeAll(sell.getSellPokers()); if(pokers.size() == 0) { return cursor == 0; }else { pokersList.set(cursor, pokers); Boolean suc = deduce(cursor, sell, cursor + 1, pokersList, counter); if(cursor != 0) { pokersList.set(cursor, original); return suc; } if(Math.abs(counter.get()) > DEDUCE_LIMIT) { pokersList.set(cursor, original); return counter.get() > DEDUCE_LIMIT; } if(suc != null) { counter.addAndGet((long)(suc ? 1 : -1)); } pokersList.set(cursor, original); } } return null;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/transfer/ByteKit.java
ByteKit
indexOf
class ByteKit { /** * Target byte array */ private byte[] bytes; public ByteKit(byte[] bytes) { this.bytes = bytes; } /** * Gets the index of the incoming array in the target array, not matched to return -1 * * @param bs Incoming array * @param start Matching start index * @return Match index, not match to return -1 */ public int indexOf(byte[] bs, int start) {<FILL_FUNCTION_BODY>} /** * Gets the position of the byte byte in the byte array * * @param b Byte * @param start Matching start index * @return Match index, not match to return -1 */ public int indexOf(byte b, int start) { return indexOf(new byte[]{b}, start); } }
int targetIndex = -1; if (bs == null) { return targetIndex; } for (int index = start; index < bytes.length; index++) { byte cbyte = bytes[index]; if (bs[0] == cbyte) { boolean isEquals = true; for (int sindex = 1; sindex < bs.length; sindex++) { if (index + sindex >= bytes.length || bs[sindex] != bytes[index + sindex]) { isEquals = false; break; } } if (isEquals) { targetIndex = index; break; } } } return targetIndex;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/transfer/ByteLink.java
ByteLink
toArray
class ByteLink { private ByteNode start; private ByteNode current; private int size; public void append(byte b) { if (start == null) { start = new ByteNode(b); current = start; } else { ByteNode node = new ByteNode(b); current.setNext(node); current = node; } size++; } public void append(byte[] bs) { if (bs != null) { for (byte b : bs) { append(b); } } } public byte[] toArray() {<FILL_FUNCTION_BODY>} public static class ByteNode { private byte b; private ByteNode next; public ByteNode(byte b) { this.b = b; } public ByteNode(byte b, ByteNode next) { this.b = b; this.next = next; } protected ByteNode clone() { return new ByteNode(b, next); } public byte getB() { return b; } public void setB(byte b) { this.b = b; } public ByteNode getNext() { return next; } public void setNext(ByteNode next) { this.next = next; } } }
if (size == 0) { return null; } byte[] bytes = new byte[size]; int index = 0; ByteNode s = start.clone(); while (s != null) { bytes[index++] = s.getB(); s = s.getNext(); } return bytes;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/transfer/TransferProtocolUtils.java
TransferProtocolUtils
unserialize
class TransferProtocolUtils { /** * A protocol header that represents the beginning of an available stream of data */ public static final byte PROTOCOL_HAED = "#".getBytes()[0]; /** * The end of the protocol used to represent the end of an available stream of data */ public static final byte PROTOCOL_TAIL = "$".getBytes()[0]; /** * Serialize the poker list to transportable bytes * * @param obj Poker list * @return Transportable byte array */ public static byte[] serialize(Object obj) { ByteLink bl = new ByteLink(); bl.append(PROTOCOL_HAED); bl.append(Noson.reversal(obj).getBytes()); bl.append(PROTOCOL_TAIL); return bl.toArray(); } /** * Deserialize the byte stream as an object * * @param bytes Byte array * @return Genericity */ public static <T> T unserialize(byte[] bytes, Class<T> clazz) {<FILL_FUNCTION_BODY>} }
ByteKit bk = new ByteKit(bytes); int start = -1; int end = -1; int index = bk.indexOf(PROTOCOL_HAED, 0); if (index != -1) start = index + 1; index = bk.indexOf(PROTOCOL_TAIL, 0); if (index != -1) end = index; if (start != -1 && end != -1 && start > end) { throw new LandlordException("Message format error, head and tail error."); } else { byte[] content = new byte[end - start]; System.arraycopy(bytes, start, content, 0, content.length); return Noson.convert(new String(content), clazz); }
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/utils/LastCardsUtils.java
LastCardsUtils
getLastCards
class LastCardsUtils { private static final List<String> defSort = new ArrayList(){{ add("3"); add("4"); add("5"); add("6"); add("7"); add("8"); add("9"); add("10"); add("J"); add("Q"); add("K"); add("A"); add("2"); add("S"); add("X"); }}; public static String getLastCards(List<List<Poker>> pokers){<FILL_FUNCTION_BODY>} private static Map<String, Integer> initLastCards(){ Map<String, Integer> lastCardMap = new HashMap<>(); lastCardMap.put("A",0); lastCardMap.put("2",0); lastCardMap.put("3",0); lastCardMap.put("4",0); lastCardMap.put("5",0); lastCardMap.put("6",0); lastCardMap.put("7",0); lastCardMap.put("8",0); lastCardMap.put("9",0); lastCardMap.put("10",0); lastCardMap.put("J",0); lastCardMap.put("Q",0); lastCardMap.put("K",0); lastCardMap.put("S",0); lastCardMap.put("X",0); return lastCardMap; } }
StringBuffer lastCards = new StringBuffer(); Map<String, Integer> lastCardMap = initLastCards(); for(int i = 0; i < pokers.size(); i++){ List<Poker> pokerList = pokers.get(i); for(int a = 0; a < pokerList.size(); a++){ Poker poker = pokerList.get(a); lastCardMap.put(poker.getLevel().getName(),(lastCardMap.get(poker.getLevel().getName())+1)); } } for(int i = 0; i < defSort.size(); i++){ String key = defSort.get(i); lastCards.append(key + "["+lastCardMap.get(key)+"] "); } return lastCards.toString();
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/utils/ListUtils.java
ListUtils
getList
class ListUtils { public static <T> List<T> getList(T[] array) {<FILL_FUNCTION_BODY>} public static <T> List<T> getList(List<T>[] array) { List<T> list = new ArrayList<>(array.length); for (List<T> t : array) { list.addAll(t); } return list; } public static <T> List<T> getList(List<T> source) { List<T> list = new ArrayList<>(source.size()); list.addAll(source); return list; } }
List<T> list = new ArrayList<>(array.length); Collections.addAll(list, array); return list;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/utils/OptionsUtils.java
OptionsUtils
getOptions
class OptionsUtils { public static int getOptions(String line) {<FILL_FUNCTION_BODY>} }
int option = -1; try { option = Integer.parseInt(line); } catch (Exception ignored) {} return option;
ainilili_ratel
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/utils/StreamUtils.java
StreamUtils
convertToString
class StreamUtils { /** * Convert input stream to string * * @param inStream Input stream * @return {@link String} */ public static String convertToString(InputStream inStream) {<FILL_FUNCTION_BODY>} public static String convertToString(URL url) throws IOException { URLConnection con = url.openConnection(); con.setUseCaches(false); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36"); return convertToString(con.getInputStream()); } }
BufferedReader br = new BufferedReader(new InputStreamReader(inStream)); StringBuilder reqStr = new StringBuilder(); char[] buf = new char[2048]; int len; try { while ((len = br.read(buf)) != -1) { reqStr.append(new String(buf, 0, len)); } br.close(); } catch (IOException e) { return null; } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return reqStr.toString();
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/ServerContains.java
ServerContains
getRoom
class ServerContains { /** * Server port */ public static int port = 1024; /** * The map of server side */ private final static Map<Integer, Room> ROOM_MAP = new ConcurrentSkipListMap<>(); /** * The list of client side */ public final static Map<Integer, ClientSide> CLIENT_SIDE_MAP = new ConcurrentSkipListMap<>(); public final static Map<String, Integer> CHANNEL_ID_MAP = new ConcurrentHashMap<>(); private final static AtomicInteger CLIENT_ATOMIC_ID = new AtomicInteger(1); private final static AtomicInteger SERVER_ATOMIC_ID = new AtomicInteger(1); public final static int getClientId() { return CLIENT_ATOMIC_ID.getAndIncrement(); } public final static int getServerId() { return SERVER_ATOMIC_ID.getAndIncrement(); } public final static ThreadPoolExecutor THREAD_EXCUTER = new ThreadPoolExecutor(500, 500, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); /** * Get room by id, with flush time * * @param id room id * @return */ public static Room getRoom(int id) {<FILL_FUNCTION_BODY>} public static Map<Integer, Room> getRoomMap() { return ROOM_MAP; } public static Room removeRoom(int id) { return ROOM_MAP.remove(id); } public static Room addRoom(Room room) { return ROOM_MAP.put(room.getId(), room); } }
Room room = ROOM_MAP.get(id); if (room != null) { room.setLastFlushTime(System.currentTimeMillis()); } return room;
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/SimpleServer.java
SimpleServer
main
class SimpleServer { public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>} }
if (args != null && args.length > 1) { if (args[0].equalsIgnoreCase("-p") || args[0].equalsIgnoreCase("-port")) { ServerContains.port = Integer.parseInt(args[1]); } } new Thread(() -> { try { new ProtobufProxy().start(ServerContains.port); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new WebsocketProxy().start(ServerContains.port + 1);
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_CLIENT_EXIT.java
ServerEventListener_CODE_CLIENT_EXIT
notifyWatcherClientExit
class ServerEventListener_CODE_CLIENT_EXIT implements ServerEventListener { private static final Object locked = new Object(); @Override public void call(ClientSide clientSide, String data) { synchronized (locked){ Room room = ServerContains.getRoom(clientSide.getRoomId()); if (room == null) { return; } String result = MapHelper.newInstance() .put("roomId", room.getId()) .put("exitClientId", clientSide.getId()) .put("exitClientNickname", clientSide.getNickname()) .json(); for (ClientSide client : room.getClientSideList()) { if (client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_CLIENT_EXIT, result); client.init(); } } notifyWatcherClientExit(room, clientSide); ServerContains.removeRoom(room.getId()); } } /** * 通知所有观战者玩家退出游戏 * * @param room 房间 * @param player 退出游戏玩家 */ private void notifyWatcherClientExit(Room room, ClientSide player) {<FILL_FUNCTION_BODY>} }
for (ClientSide watcher : room.getWatcherList()) { ChannelUtils.pushToClient(watcher.getChannel(), ClientEventCode.CODE_CLIENT_EXIT, player.getNickname()); }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_CLIENT_INFO_SET.java
ServerEventListener_CODE_CLIENT_INFO_SET
call
class ServerEventListener_CODE_CLIENT_INFO_SET implements ServerEventListener { private static final String DEFAULT_VERSION = "v1.2.8"; @Override public void call(ClientSide client, String info) {<FILL_FUNCTION_BODY>} }
Map<?,?> infos = JsonUtils.fromJson(info, Map.class); // Get client version client.setVersion(DEFAULT_VERSION); if (infos.containsKey("version")){ client.setVersion(String.valueOf(infos.get("version"))); }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_CLIENT_NICKNAME_SET.java
ServerEventListener_CODE_CLIENT_NICKNAME_SET
call
class ServerEventListener_CODE_CLIENT_NICKNAME_SET implements ServerEventListener { public static final int NICKNAME_MAX_LENGTH = 10; @Override public void call(ClientSide client, String nickname) {<FILL_FUNCTION_BODY>} }
if (nickname.trim().length() > NICKNAME_MAX_LENGTH || nickname.trim().isEmpty()) { String result = MapHelper.newInstance().put("invalidLength", nickname.trim().length()).json(); ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_CLIENT_NICKNAME_SET, result); return; } ServerContains.CLIENT_SIDE_MAP.get(client.getId()).setNickname(nickname); ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_SHOW_OPTIONS, null);
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_CLIENT_OFFLINE.java
ServerEventListener_CODE_CLIENT_OFFLINE
call
class ServerEventListener_CODE_CLIENT_OFFLINE implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} }
Room room = ServerContains.getRoom(clientSide.getRoomId()); if (room == null) { ServerContains.CLIENT_SIDE_MAP.remove(clientSide.getId()); return; } if (room.getWatcherList().contains(clientSide)) { return; } String result = MapHelper.newInstance() .put("roomId", room.getId()) .put("exitClientId", clientSide.getId()) .put("exitClientNickname", clientSide.getNickname()) .json(); for (ClientSide client : room.getClientSideList()) { if (client.getRole() != ClientRole.PLAYER) { continue; } if (client.getId() != clientSide.getId()) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_CLIENT_EXIT, result); client.init(); } } ServerContains.removeRoom(room.getId());
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_LANDLORD_ELECT.java
ServerEventListener_CODE_GAME_LANDLORD_ELECT
call
class ServerEventListener_CODE_GAME_LANDLORD_ELECT implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} public void confirmLandlord(ClientSide clientSide, Room room) { clientSide.getPokers().addAll(room.getLandlordPokers()); PokerHelper.sortPoker(clientSide.getPokers()); int currentClientId = clientSide.getId(); room.setLandlordId(currentClientId); room.setLastSellClient(currentClientId); room.setCurrentSellClient(currentClientId); clientSide.setType(ClientType.LANDLORD); for (ClientSide client : room.getClientSideList()) { String result = MapHelper.newInstance() .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .put("roomClientCount", room.getClientSideList().size()) .put("landlordNickname", clientSide.getNickname()) .put("landlordId", clientSide.getId()) .put("additionalPokers", room.getLandlordPokers()) .put("baseScore", room.getBaseScore()) .json(); client.resetRound(); if (client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_GAME_LANDLORD_CONFIRM, result); continue; } if (currentClientId == client.getId()) { RobotEventListener.get(ClientEventCode.CODE_GAME_POKER_PLAY).call(client, result); } } notifyWatcherConfirmLandlord(room, clientSide); } /** * 通知房间内的观战人员谁是地主 * * @param room 房间 * @param landlord 地主 */ private void notifyWatcherConfirmLandlord(Room room, ClientSide landlord) { String json = MapHelper.newInstance() .put("landlord", landlord.getNickname()) .put("additionalPokers", room.getLandlordPokers()) .json(); for (ClientSide watcher : room.getWatcherList()) { ChannelUtils.pushToClient(watcher.getChannel(), ClientEventCode.CODE_GAME_LANDLORD_CONFIRM, json); } } /** * 通知房间内的观战人员抢地主情况 * * @param room 房间 */ private void notifyWatcherRobLandlord(Room room, ClientSide player) { for (ClientSide watcher : room.getWatcherList()) { ChannelUtils.pushToClient(watcher.getChannel(), ClientEventCode.CODE_GAME_LANDLORD_ELECT, player.getNickname()); } } }
Room room = ServerContains.getRoom(clientSide.getRoomId()); Map<String, Object> map = MapHelper.parser(data); int highestScore = (Integer)map.get("highestScore"); if (room == null) { return; } if (highestScore == 3) { room.setBaseScore(highestScore); confirmLandlord(clientSide, room); return; } if (clientSide.getNext().getId() == room.getFirstSellClient()) { if (highestScore == 0) { for (ClientSide client : room.getClientSideList()) { if (client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_GAME_LANDLORD_CYCLE, null); } } ServerEventListener.get(ServerEventCode.CODE_GAME_STARTING).call(clientSide, null); return; } else { room.setBaseScore(highestScore); int landlordId = (Integer)map.get("currentLandlordId"); for (ClientSide client : room.getClientSideList()) if (client.getId() == landlordId) { confirmLandlord(client, room); return; } } } ClientSide turnClientSide = clientSide.getNext(); room.setCurrentSellClient(turnClientSide.getId()); String result; if (highestScore != 0) { result = MapHelper.newInstance() .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .put("roomClientCount", room.getClientSideList().size()) .put("preClientNickname", clientSide.getNickname()) .put("preClientId", clientSide.getId()) .put("nextClientNickname", turnClientSide.getNickname()) .put("nextClientId", turnClientSide.getId()) .put("highestScore", highestScore) .put("currentLandlordId", (Integer)map.get("currentLandlordId")) .json(); } else { result = MapHelper.newInstance() .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .put("roomClientCount", room.getClientSideList().size()) .put("preClientNickname", clientSide.getNickname()) .put("nextClientNickname", turnClientSide.getNickname()) .put("nextClientId", turnClientSide.getId()) .put("highestScore", 0) .json(); } for (ClientSide client : room.getClientSideList()) { if (client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_GAME_LANDLORD_ELECT, result); continue; } if (client.getId() == turnClientSide.getId()) { RobotEventListener.get(ClientEventCode.CODE_GAME_LANDLORD_ELECT).call(client, result); } } notifyWatcherRobLandlord(room, clientSide);
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_POKER_PLAY_PASS.java
ServerEventListener_CODE_GAME_POKER_PLAY_PASS
call
class ServerEventListener_CODE_GAME_POKER_PLAY_PASS implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} /** * 通知观战者玩家不出牌 * * @param room 房间 * @param player 不出牌的玩家 */ private void notifyWatcherPlayPass(Room room, ClientSide player) { for (ClientSide watcher : room.getWatcherList()) { ChannelUtils.pushToClient(watcher.getChannel(), ClientEventCode.CODE_GAME_POKER_PLAY_PASS, player.getNickname()); } } }
Room room = ServerContains.getRoom(clientSide.getRoomId()); if(room != null) { if(room.getCurrentSellClient() == clientSide.getId()) { if(clientSide.getId() != room.getLastSellClient()) { ClientSide turnClient = clientSide.getNext(); room.setCurrentSellClient(turnClient.getId()); for(ClientSide client: room.getClientSideList()) { String result = MapHelper.newInstance() .put("clientId", clientSide.getId()) .put("clientNickname", clientSide.getNickname()) .put("nextClientId", turnClient.getId()) .put("nextClientNickname", turnClient.getNickname()) .json(); if(client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_GAME_POKER_PLAY_PASS, result); }else { if(client.getId() == turnClient.getId()) { RobotEventListener.get(ClientEventCode.CODE_GAME_POKER_PLAY).call(turnClient, data); } } } notifyWatcherPlayPass(room, clientSide); }else { ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_GAME_POKER_PLAY_CANT_PASS, null); } }else { ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_GAME_POKER_PLAY_ORDER_ERROR, null); } }else { // ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_ROOM_PLAY_FAIL_BY_INEXIST, null); }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_POKER_PLAY_REDIRECT.java
ServerEventListener_CODE_GAME_POKER_PLAY_REDIRECT
call
class ServerEventListener_CODE_GAME_POKER_PLAY_REDIRECT implements ServerEventListener{ @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} }
Room room = ServerContains.getRoom(clientSide.getRoomId()); Map<String, Object> datas = new HashMap<String, Object>(); if(StringUtils.isNotBlank(data)) { datas = Noson.parseMap(data); } List<Map<String, Object>> clientInfos = new ArrayList<Map<String,Object>>(3); for(ClientSide client : room.getClientSideList()) { if(clientSide.getId() != client.getId()) { clientInfos.add(MapHelper.newInstance() .put("clientId", client.getId()) .put("clientNickname", client.getNickname()) .put("type", client.getType()) .put("surplus", client.getPokers().size()) .put("position", clientSide.getPre().getId() == client.getId() ? "UP" : "DOWN") .map()); } } List<List<Poker>> lastPokerList = new ArrayList<>(); for(int i = 0; i < room.getClientSideList().size(); i++){ if(room.getClientSideList().get(i).getId() != clientSide.getId()){ lastPokerList.add(room.getClientSideList().get(i).getPokers()); } } String lastPokers = LastCardsUtils.getLastCards(lastPokerList); lastPokerList = new ArrayList<>(); String result = MapHelper.newInstance() .put("pokers", clientSide.getPokers()) .put("lastSellPokers", datas.get("lastSellPokers")) .put("lastSellClientId", datas.get("lastSellClientId")) .put("clientInfos", clientInfos) .put("sellClientId", room.getCurrentSellClient()) .put("sellClientNickname", ServerContains.CLIENT_SIDE_MAP.get(room.getCurrentSellClient()).getNickname()) .put("lastPokers",lastPokers) .json(); ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_GAME_POKER_PLAY_REDIRECT, result);
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_READY.java
ServerEventListener_CODE_GAME_READY
call
class ServerEventListener_CODE_GAME_READY implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} }
Room room = ServerContains.getRoom(clientSide.getRoomId()); if (room == null) { return; } SimplePrinter.serverLog("房间状态:" + room.getStatus()); SimplePrinter.serverLog("玩家状态:" + clientSide.getStatus()); if (room.getStatus() == RoomStatus.STARTING) { return; } if (clientSide.getStatus() == ClientStatus.PLAYING || clientSide.getStatus() == ClientStatus.TO_CHOOSE || clientSide.getStatus() == ClientStatus.CALL_LANDLORD) { return; } clientSide.setStatus(clientSide.getStatus() == ClientStatus.READY ? ClientStatus.NO_READY : ClientStatus.READY); String result = MapHelper.newInstance() .put("clientNickName", clientSide.getNickname()) .put("status", clientSide.getStatus()) .put("clientId", clientSide.getId()) .json(); boolean allReady = true; ConcurrentSkipListMap<Integer, ClientSide> roomClientMap = (ConcurrentSkipListMap<Integer, ClientSide>) room.getClientSideMap(); if (roomClientMap.size() < 3) { allReady = false; } else { for (ClientSide client : room.getClientSideList()) { if (client.getRole() == ClientRole.PLAYER && client.getStatus() != ClientStatus.READY) { allReady = false; break; } } } for (ClientSide client : room.getClientSideList()) { if (client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_GAME_READY, result); } } if (allReady) { ServerEventListener.get(ServerEventCode.CODE_GAME_STARTING).call(clientSide, data); }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_STARTING.java
ServerEventListener_CODE_GAME_STARTING
call
class ServerEventListener_CODE_GAME_STARTING implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} /** * 通知房间内的观战人员游戏开始 * * @param room 房间 */ private void notifyWatcherGameStart(Room room) { String result = MapHelper.newInstance() .put("player1", room.getClientSideList().getFirst().getNickname()) .put("player2", room.getClientSideList().getFirst().getNext().getNickname()) .put("player3", room.getClientSideList().getLast().getNickname()) .json(); for (ClientSide clientSide : room.getWatcherList()) { ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_GAME_STARTING, result); } } }
Room room = ServerContains.getRoom(clientSide.getRoomId()); LinkedList<ClientSide> roomClientList = room.getClientSideList(); // Send the points of poker List<List<Poker>> pokersList = PokerHelper.distributePoker(); int cursor = 0; for (ClientSide client : roomClientList) { client.setPokers(pokersList.get(cursor++)); } room.setLandlordPokers(pokersList.get(3)); // Push information about the robber int startGrabIndex = (int) (Math.random() * 3); ClientSide startGrabClient = roomClientList.get(startGrabIndex); room.setCurrentSellClient(startGrabClient.getId()); // Push start game messages room.setStatus(RoomStatus.STARTING); room.setCreateTime(System.currentTimeMillis()); room.setLastFlushTime(System.currentTimeMillis()); // Record the first speaker room.setFirstSellClient(startGrabClient.getId()); List<List<Poker>> otherPokers = new ArrayList<>(); for (ClientSide client : roomClientList) { client.setType(ClientType.PEASANT); client.setStatus(ClientStatus.PLAYING); for(ClientSide otherClient : roomClientList){ if(otherClient.getId() != client.getId()){ otherPokers.add(otherClient.getPokers()); } } otherPokers.add(room.getLandlordPokers()); String lastCards = LastCardsUtils.getLastCards(otherPokers); otherPokers = new ArrayList<>(); String result = MapHelper.newInstance() .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .put("roomClientCount", room.getClientSideList().size()) .put("nextClientNickname", startGrabClient.getNickname()) .put("nextClientId", startGrabClient.getId()) .put("pokers", client.getPokers()) .put("lastPokers",lastCards) .put("highestScore", 0) .json(); if (client.getRole() == ClientRole.PLAYER) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_GAME_STARTING, result); } else { if (startGrabClient.getId() == client.getId()) { RobotEventListener.get(ClientEventCode.CODE_GAME_LANDLORD_ELECT).call(client, result); } } } notifyWatcherGameStart(room);
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_WATCH.java
ServerEventListener_CODE_GAME_WATCH
call
class ServerEventListener_CODE_GAME_WATCH implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} }
Room room = ServerContains.getRoom(Integer.parseInt(data)); if (room == null) { String result = MapHelper.newInstance() .put("roomId", data) .json(); ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_ROOM_JOIN_FAIL_BY_INEXIST, result); } else { // 将用户加入到房间中的观战者列表中 clientSide.setRoomId(room.getId()); room.getWatcherList().add(clientSide); Map<String, String> map = new HashMap<>(16); map.put("owner", room.getRoomOwner()); map.put("status", room.getStatus().toString()); ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_GAME_WATCH_SUCCESSFUL, Noson.reversal(map)); }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GAME_WATCH_EXIT.java
ServerEventListener_CODE_GAME_WATCH_EXIT
call
class ServerEventListener_CODE_GAME_WATCH_EXIT implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} }
Room room = ServerContains.getRoom(clientSide.getRoomId()); if (room != null) { // 房间如果存在,则将观战者从房间观战列表中移除 clientSide.setRoomId(room.getId()); boolean successful = room.getWatcherList().remove(clientSide); if (successful) { SimplePrinter.serverLog(clientSide.getNickname() + " exit room " + room.getId()); } }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_GET_ROOMS.java
ServerEventListener_CODE_GET_ROOMS
call
class ServerEventListener_CODE_GET_ROOMS implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} }
List<Map<String, Object>> roomList = new ArrayList<>(ServerContains.getRoomMap().size()); for (Entry<Integer, Room> entry : ServerContains.getRoomMap().entrySet()) { Room room = entry.getValue(); roomList.add(MapHelper.newInstance() .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .put("roomClientCount", room.getClientSideList().size()) .put("roomType", room.getType()) .map()); } ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_SHOW_ROOMS, Noson.reversal(roomList));
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_ROOM_CREATE.java
ServerEventListener_CODE_ROOM_CREATE
call
class ServerEventListener_CODE_ROOM_CREATE implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} }
Room room = new Room(ServerContains.getServerId()); room.setStatus(RoomStatus.WAIT); room.setType(RoomType.PVP); room.setRoomOwner(clientSide.getNickname()); room.getClientSideMap().put(clientSide.getId(), clientSide); room.getClientSideList().add(clientSide); room.setCurrentSellClient(clientSide.getId()); room.setCreateTime(System.currentTimeMillis()); room.setLastFlushTime(System.currentTimeMillis()); clientSide.setRoomId(room.getId()); ServerContains.addRoom(room); clientSide.setStatus(ClientStatus.NO_READY); ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_ROOM_CREATE_SUCCESS, Noson.reversal(room));
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_ROOM_CREATE_PVE.java
ServerEventListener_CODE_ROOM_CREATE_PVE
call
class ServerEventListener_CODE_ROOM_CREATE_PVE implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} }
int difficultyCoefficient = Integer.parseInt(data); if (!RobotDecisionMakers.contains(difficultyCoefficient)) { ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_PVE_DIFFICULTY_NOT_SUPPORT, null); return; } Room room = new Room(ServerContains.getServerId()); room.setType(RoomType.PVE); room.setStatus(RoomStatus.BLANK); room.setRoomOwner(clientSide.getNickname()); room.getClientSideMap().put(clientSide.getId(), clientSide); room.getClientSideList().add(clientSide); room.setCurrentSellClient(clientSide.getId()); room.setCreateTime(System.currentTimeMillis()); room.setDifficultyCoefficient(difficultyCoefficient); clientSide.setRoomId(room.getId()); ServerContains.addRoom(room); ClientSide preClient = clientSide; //Add robots for (int index = 1; index < 3; index++) { ClientSide robot = new ClientSide(-ServerContains.getClientId(), ClientStatus.PLAYING, null); robot.setNickname("robot_" + index); robot.setRole(ClientRole.ROBOT); preClient.setNext(robot); robot.setPre(preClient); robot.setRoomId(room.getId()); room.getClientSideMap().put(robot.getId(), robot); room.getClientSideList().add(robot); preClient = robot; ServerContains.CLIENT_SIDE_MAP.put(robot.getId(), robot); } preClient.setNext(clientSide); clientSide.setPre(preClient); ServerEventListener.get(ServerEventCode.CODE_GAME_STARTING).call(clientSide, String.valueOf(room.getId()));
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_ROOM_JOIN.java
ServerEventListener_CODE_ROOM_JOIN
call
class ServerEventListener_CODE_ROOM_JOIN implements ServerEventListener { @Override public void call(ClientSide clientSide, String data) {<FILL_FUNCTION_BODY>} /** * 通知观战者玩家加入房间 * * @param room 房间 * @param clientSide 玩家 */ private void notifyWatcherJoinRoom(Room room, ClientSide clientSide) { for (ClientSide watcher : room.getWatcherList()) { ChannelUtils.pushToClient(watcher.getChannel(), ClientEventCode.CODE_ROOM_JOIN_SUCCESS, clientSide.getNickname()); } } }
Room room = ServerContains.getRoom(Integer.parseInt(data)); if (room == null) { String result = MapHelper.newInstance() .put("roomId", data) .json(); ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_ROOM_JOIN_FAIL_BY_INEXIST, result); return; } if (room.getClientSideList().size() == 3) { String result = MapHelper.newInstance() .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .json(); ChannelUtils.pushToClient(clientSide.getChannel(), ClientEventCode.CODE_ROOM_JOIN_FAIL_BY_FULL, result); return; } // join default ready clientSide.setStatus(ClientStatus.READY); clientSide.setRoomId(room.getId()); ConcurrentSkipListMap<Integer, ClientSide> roomClientMap = (ConcurrentSkipListMap<Integer, ClientSide>) room.getClientSideMap(); LinkedList<ClientSide> roomClientList = room.getClientSideList(); if (roomClientList.size() > 0) { ClientSide pre = roomClientList.getLast(); pre.setNext(clientSide); clientSide.setPre(pre); } roomClientList.add(clientSide); roomClientMap.put(clientSide.getId(), clientSide); room.setStatus(RoomStatus.WAIT); String result = MapHelper.newInstance() .put("clientId", clientSide.getId()) .put("clientNickname", clientSide.getNickname()) .put("roomId", room.getId()) .put("roomOwner", room.getRoomOwner()) .put("roomClientCount", room.getClientSideList().size()) .json(); for (ClientSide client : roomClientMap.values()) { ChannelUtils.pushToClient(client.getChannel(), ClientEventCode.CODE_ROOM_JOIN_SUCCESS, result); } if (roomClientMap.size() == 3) { clientSide.setNext(roomClientList.getFirst()); roomClientList.getFirst().setPre(clientSide); ServerEventListener.get(ServerEventCode.CODE_GAME_STARTING).call(clientSide, String.valueOf(room.getId())); return; } notifyWatcherJoinRoom(room, clientSide);
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/handler/ProtobufTransferHandler.java
ProtobufTransferHandler
channelRead
class ProtobufTransferHandler extends ChannelInboundHandlerAdapter { @Override public void handlerRemoved(ChannelHandlerContext ctx) { ClientSide client = ServerContains.CLIENT_SIDE_MAP.get(getId(ctx.channel())); SimplePrinter.serverLog("client " + client.getId() + "(" + client.getNickname() + ") disconnected"); clientOfflineEvent(ctx.channel()); ctx.channel().close(); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { Channel ch = ctx.channel(); //init client info ClientSide clientSide = new ClientSide(getId(ctx.channel()), ClientStatus.TO_CHOOSE, ch); clientSide.setNickname(String.valueOf(clientSide.getId())); clientSide.setRole(ClientRole.PLAYER); ServerContains.CLIENT_SIDE_MAP.put(clientSide.getId(), clientSide); SimplePrinter.serverLog("Has client connect to the server: " + clientSide.getId()); ChannelUtils.pushToClient(ch, ClientEventCode.CODE_CLIENT_CONNECT, String.valueOf(clientSide.getId())); ChannelUtils.pushToClient(ch, ClientEventCode.CODE_CLIENT_NICKNAME_SET, null); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {<FILL_FUNCTION_BODY>} @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state() == IdleState.READER_IDLE) { try { clientOfflineEvent(ctx.channel()); ctx.channel().close(); } catch (Exception ignore) { } } } else { super.userEventTriggered(ctx, evt); } } private int getId(Channel channel) { String longId = channel.id().asLongText(); Integer clientId = ServerContains.CHANNEL_ID_MAP.get(longId); if (null == clientId) { clientId = ServerContains.getClientId(); ServerContains.CHANNEL_ID_MAP.put(longId, clientId); } return clientId; } private void clientOfflineEvent(Channel channel) { int clientId = getId(channel); ClientSide client = ServerContains.CLIENT_SIDE_MAP.get(clientId); if (client != null) { SimplePrinter.serverLog("Has client exit to the server:" + clientId + " | " + client.getNickname()); ServerEventListener.get(ServerEventCode.CODE_CLIENT_OFFLINE).call(client, null); } } }
if (msg instanceof ServerTransferDataProtoc) { ServerTransferDataProtoc serverTransferData = (ServerTransferDataProtoc) msg; ServerEventCode code = ServerEventCode.valueOf(serverTransferData.getCode()); if (code != ServerEventCode.CODE_CLIENT_HEAD_BEAT) { ClientSide client = ServerContains.CLIENT_SIDE_MAP.get(getId(ctx.channel())); SimplePrinter.serverLog(client.getId() + " | " + client.getNickname() + " do:" + code.getMsg()); ServerEventListener.get(code).call(client, serverTransferData.getData()); } }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/handler/WebsocketTransferHandler.java
WebsocketTransferHandler
getId
class WebsocketTransferHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception { Msg msg = JsonUtils.fromJson(frame.text(), Msg.class); ServerEventCode code = ServerEventCode.valueOf(msg.getCode()); if (!Objects.equals(code, ServerEventCode.CODE_CLIENT_HEAD_BEAT)) { ClientSide client = ServerContains.CLIENT_SIDE_MAP.get(getId(ctx.channel())); SimplePrinter.serverLog(client.getId() + " | " + client.getNickname() + " do:" + code.getMsg()); ServerEventListener.get(code).call(client, msg.getData()); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof java.io.IOException) { clientOfflineEvent(ctx.channel()); } else { SimplePrinter.serverLog("ERROR:" + cause.getMessage()); cause.printStackTrace(); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state() == IdleState.READER_IDLE) { try { clientOfflineEvent(ctx.channel()); ctx.channel().close(); } catch (Exception e) { } } } else if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) { Channel ch = ctx.channel(); // init client info ClientSide clientSide = new ClientSide(getId(ctx.channel()), ClientStatus.TO_CHOOSE, ch); clientSide.setNickname(String.valueOf(clientSide.getId())); clientSide.setRole(ClientRole.PLAYER); ServerContains.CLIENT_SIDE_MAP.put(clientSide.getId(), clientSide); SimplePrinter.serverLog("Has client connect to the server:" + clientSide.getId()); new Thread(() -> { try { Thread.sleep(2000L); ChannelUtils.pushToClient(ch, ClientEventCode.CODE_CLIENT_CONNECT, String.valueOf(clientSide.getId())); ChannelUtils.pushToClient(ch, ClientEventCode.CODE_CLIENT_NICKNAME_SET, null); } catch (InterruptedException ignored) { } }).start(); } else { super.userEventTriggered(ctx, evt); } } private int getId(Channel channel) {<FILL_FUNCTION_BODY>} private void clientOfflineEvent(Channel channel) { int clientId = getId(channel); ClientSide client = ServerContains.CLIENT_SIDE_MAP.get(clientId); if (client != null) { SimplePrinter.serverLog("Has client exit to the server:" + clientId + " | " + client.getNickname()); ServerEventListener.get(ServerEventCode.CODE_CLIENT_OFFLINE).call(client, null); } } }
String longId = channel.id().asLongText(); Integer clientId = ServerContains.CHANNEL_ID_MAP.get(longId); if (null == clientId) { clientId = ServerContains.getClientId(); ServerContains.CHANNEL_ID_MAP.put(longId, clientId); } return clientId;
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/proxy/ProtobufProxy.java
ProtobufProxy
start
class ProtobufProxy implements Proxy{ @Override public void start(int port) throws InterruptedException {<FILL_FUNCTION_BODY>} }
EventLoopGroup parentGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup(); EventLoopGroup childGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(parentGroup, childGroup) .channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new IdleStateHandler(60 * 30, 0, 0, TimeUnit.SECONDS)) .addLast(new ProtobufVarint32FrameDecoder()) .addLast(new ProtobufDecoder(ServerTransferData.ServerTransferDataProtoc.getDefaultInstance())) .addLast(new ProtobufVarint32LengthFieldPrepender()) .addLast(new ProtobufEncoder()) .addLast(new SecondProtobufCodec()) .addLast(new ProtobufTransferHandler()); } }); ChannelFuture f = bootstrap .bind().sync(); SimplePrinter.serverLog("The protobuf server was successfully started on port " + port); //Init robot. RobotDecisionMakers.init(); ServerContains.THREAD_EXCUTER.execute(() -> { Timer timer=new Timer(); timer.schedule(new RoomClearTask(), 0L, 3000L); }); f.channel().closeFuture().sync(); } finally { parentGroup.shutdownGracefully(); childGroup.shutdownGracefully(); }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/proxy/WebsocketProxy.java
WebsocketProxy
start
class WebsocketProxy implements Proxy{ @Override public void start(int port) throws InterruptedException {<FILL_FUNCTION_BODY>} }
EventLoopGroup parentGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup(); EventLoopGroup childGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(parentGroup, childGroup) .channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new IdleStateHandler(60 * 30, 0, 0, TimeUnit.SECONDS)) .addLast(new HttpServerCodec()) .addLast(new ChunkedWriteHandler()) .addLast(new HttpObjectAggregator(8192)) .addLast("ws", new WebSocketServerProtocolHandler("/ratel")) .addLast(new WebsocketTransferHandler()); } }); ChannelFuture f = bootstrap .bind().sync(); SimplePrinter.serverLog("The websocket server was successfully started on port " + port); //Init robot. RobotDecisionMakers.init(); f.channel().closeFuture().sync(); } finally { parentGroup.shutdownGracefully(); childGroup.shutdownGracefully(); }
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/robot/RobotEventListener_CODE_GAME_LANDLORD_ELECT.java
RobotEventListener_CODE_GAME_LANDLORD_ELECT
call
class RobotEventListener_CODE_GAME_LANDLORD_ELECT implements RobotEventListener { @Override public void call(ClientSide robot, String data) {<FILL_FUNCTION_BODY>} }
ServerContains.THREAD_EXCUTER.execute(() -> { Room room = ServerContains.getRoom(robot.getRoomId()); List<Poker> landlordPokers = new ArrayList<>(20); landlordPokers.addAll(robot.getPokers()); landlordPokers.addAll(room.getLandlordPokers()); List<Poker> leftPokers = new ArrayList<>(17); leftPokers.addAll(robot.getPre().getPokers()); List<Poker> rightPokers = new ArrayList<>(17); rightPokers.addAll(robot.getNext().getPokers()); PokerHelper.sortPoker(landlordPokers); PokerHelper.sortPoker(leftPokers); PokerHelper.sortPoker(rightPokers); TimeHelper.sleep(300); Map<String, Object> map = MapHelper.parser(data); int expectedScore = RobotDecisionMakers.getLandlordScore(room.getDifficultyCoefficient(), leftPokers, rightPokers, landlordPokers); int highestScore = (Integer)map.get("highestScore"); String result; if (expectedScore > highestScore) { result = MapHelper.newInstance() .put("highestScore", expectedScore) .put("currentLandlordId", robot.getId()) .json(); } else { result = data; } ServerEventListener.get(ServerEventCode.CODE_GAME_LANDLORD_ELECT).call(robot, result); });
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/robot/RobotEventListener_CODE_GAME_POKER_PLAY.java
RobotEventListener_CODE_GAME_POKER_PLAY
call
class RobotEventListener_CODE_GAME_POKER_PLAY implements RobotEventListener { @Override public void call(ClientSide robot, String data) {<FILL_FUNCTION_BODY>} }
ServerContains.THREAD_EXCUTER.execute(() -> { Room room = ServerContains.getRoom(robot.getRoomId()); PokerSell lastPokerSell = null; PokerSell pokerSell = null; if (room.getLastSellClient() != robot.getId()) { lastPokerSell = room.getLastPokerShell(); pokerSell = RobotDecisionMakers.howToPlayPokers(room.getDifficultyCoefficient(), lastPokerSell, robot); } else { pokerSell = RobotDecisionMakers.howToPlayPokers(room.getDifficultyCoefficient(), null, robot); } if (pokerSell != null && lastPokerSell != null) { SimplePrinter.serverLog("Robot monitoring[room:" + room.getId() + "]"); SimplePrinter.serverLog("last sell -> " + lastPokerSell.toString()); SimplePrinter.serverLog("robot sell -> " + pokerSell.toString()); SimplePrinter.serverLog("robot poker -> " + PokerHelper.textOnlyNoType(robot.getPokers())); } TimeHelper.sleep(300); if (pokerSell == null || pokerSell.getSellType() == SellType.ILLEGAL) { ServerEventListener.get(ServerEventCode.CODE_GAME_POKER_PLAY_PASS).call(robot, data); } else { Character[] cs = new Character[pokerSell.getSellPokers().size()]; for (int index = 0; index < cs.length; index++) { cs[index] = pokerSell.getSellPokers().get(index).getLevel().getAlias()[0]; } ServerEventListener.get(ServerEventCode.CODE_GAME_POKER_PLAY).call(robot, Noson.reversal(cs)); } });
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/timer/RoomClearTask.java
RoomClearTask
doing
class RoomClearTask extends TimerTask { //The room wait time of after create is 100s private static final long waitingStatusInterval = 1000 * 100; //The room starting destroy time is 100s private static final long startingStatusInterval = 1000 * 300; //The room live time is 600s private static final long liveTime = 1000 * 60 * 20; @Override public void run() { try { doing(); } catch (Exception e) { SimplePrinter.serverLog(e.getMessage()); } } public void doing() {<FILL_FUNCTION_BODY>} /** * 通知观战者玩家被提出房间 * * @param room 房间 * @param player 被提出的玩家 */ private void notifyWatcherClientKick(Room room, ClientSide player) { for (ClientSide watcher : room.getWatcherList()) { ChannelUtils.pushToClient(watcher.getChannel(), ClientEventCode.CODE_CLIENT_KICK, player.getNickname()); } } }
Map<Integer, Room> rooms = ServerContains.getRoomMap(); if (rooms == null || rooms.isEmpty()) { return; } long now = System.currentTimeMillis(); for (Room room : rooms.values()) { long alreadyLiveTime = System.currentTimeMillis() - room.getCreateTime(); SimplePrinter.serverLog("room " + room.getId() + " already live " + alreadyLiveTime + "ms"); if (alreadyLiveTime > liveTime) { SimplePrinter.serverLog("room " + room.getId() + " live time overflow " + liveTime + ", closed!"); ServerEventListener.get(ServerEventCode.CODE_CLIENT_EXIT).call(room.getClientSideList().get(0), null); continue; } long diff = now - room.getLastFlushTime(); if (room.getStatus() != RoomStatus.STARTING && diff > waitingStatusInterval) { SimplePrinter.serverLog("room " + room.getId() + " starting waiting time overflow " + waitingStatusInterval + ", closed!"); ServerEventListener.get(ServerEventCode.CODE_CLIENT_EXIT).call(room.getClientSideList().get(0), null); continue; } if (room.getType() != RoomType.PVP) { continue; } if (diff <= startingStatusInterval) { continue; } boolean allRobots = true; for (ClientSide client : room.getClientSideList()) { if (client.getId() != room.getCurrentSellClient() && client.getRole() == ClientRole.PLAYER) { allRobots = false; break; } } ClientSide currentPlayer = room.getClientSideMap().get(room.getCurrentSellClient()); if (allRobots) { SimplePrinter.serverLog("room " + room.getId() + " all is robots, closed!"); ServerEventListener.get(ServerEventCode.CODE_CLIENT_EXIT).call(currentPlayer, null); continue; } //kick this client ChannelUtils.pushToClient(currentPlayer.getChannel(), ClientEventCode.CODE_CLIENT_KICK, null); notifyWatcherClientKick(room, currentPlayer); //client current player room.getClientSideMap().remove(currentPlayer.getId()); room.getClientSideList().remove(currentPlayer); ClientSide robot = new ClientSide(-ServerContains.getClientId(), ClientStatus.PLAYING, null); robot.setNickname(currentPlayer.getNickname()); robot.setRole(ClientRole.ROBOT); robot.setRoomId(room.getId()); robot.setNext(currentPlayer.getNext()); robot.setPre(currentPlayer.getPre()); robot.getNext().setPre(robot); robot.getPre().setNext(robot); robot.setPokers(currentPlayer.getPokers()); robot.setType(currentPlayer.getType()); room.getClientSideMap().put(robot.getId(), robot); room.getClientSideList().add(robot); room.setCurrentSellClient(robot.getId()); //If last sell client is current client, replace it to robot id if (room.getLastSellClient() == currentPlayer.getId()) { room.setLastSellClient(robot.getId()); } //set robot difficulty -> simple room.setDifficultyCoefficient(1); ServerContains.CLIENT_SIDE_MAP.put(robot.getId(), robot); //init client currentPlayer.init(); SimplePrinter.serverLog("room " + room.getId() + " player " + currentPlayer.getNickname() + " " + startingStatusInterval + "ms not operating, automatic custody!"); RobotEventListener.get(room.getLandlordId() == -1 ? ClientEventCode.CODE_GAME_LANDLORD_ELECT : ClientEventCode.CODE_GAME_POKER_PLAY).call(robot, null); }