Skip to content

Instantly share code, notes, and snippets.

@caotic123
Created November 25, 2019 18:16
Show Gist options
  • Save caotic123/32b39ee5ec614f4b8698633468dfa0e4 to your computer and use it in GitHub Desktop.
Save caotic123/32b39ee5ec614f4b8698633468dfa0e4 to your computer and use it in GitHub Desktop.
import java.net.*;
import java.io.*;
import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.HashMap;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class Client {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
static int tolerance = 4;
Timer timer;
private BufferedReader reader;
public class State {
State(int id) {
ID = id;
}
public int getID() {
return ID;
}
private int ID;
}
public class Player {
public Player() {
estado = Optional.empty();
}
public Boolean connected() {
return jogador.estado.isPresent();
}
public Optional<State> estado;
}
//private Function<BufferedReader, Optional<State>> continuation;
private Player jogador = new Player ();
public void startConnection(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
reader = new BufferedReader(new InputStreamReader(System.in)); // apenas alguns detalhes
}
public void solicitEnter(String msg, String name) throws IOException, InterruptedException {
timer = new Timer();
int buffer;
// System.out.print(in.readLine());
synchronized (jogador) {
out.println(msg);
out.println(name);
jogador.wait(1000*4);
try {
if (in.ready()) {
buffer = Integer.parseInt(in.readLine());
if (buffer == 0x0) {
buffer = Integer.parseInt(in.readLine());
jogador.estado = Optional.of(new State(buffer));
}
}
}
catch(Exception e) {}
}
}
public void stopConnection() throws IOException {
in.close();
out.close();
clientSocket.close();
}
void doIfYourPackageID(int d, Callable<Void> f) throws Exception {
if (d == jogador.estado.get().getID()) {
f.call();
}
}
public void StartGame() throws IOException {
HashMap<String, Integer> plays = new HashMap<>();
plays.put("pedra", 1);
plays.put("papel", 2);
plays.put("tesoura", 3);
ExecutorService executor = Executors.newCachedThreadPool();
if (jogador.connected()) {
new Thread(() ->
{
while (true) {
try {
final String buffer = in.readLine();
final int id = Integer.parseInt(in.readLine());
switch(Integer.parseInt(buffer)) {
case 0x1 :
doIfYourPackageID(id,
() -> {
final String bmsg = in.readLine();
System.out.println(bmsg);
while(true) {
final String[] msg = reader.readLine().split(";");
if (msg.length <= 0 || !(msg[0].toLowerCase().equals("sala") || (msg[0].toLowerCase().equals("lista"))) && msg.length <= 1) {
System.out.println(bmsg);
} else {
if (msg[0].toLowerCase().equals("sala")) {
// final Future<Void> wait = executor.submit(() -> {
// while(true) {
// try {
// if (in.ready()) {
// final String protocol_ = in.readLine();
// final String id_ = in.readLine();
// final String msg_ = in.readLine();
// System.out.println(msg_);
// }
// }
// catch(Exception e) {}
// }
// });
out.println(0x1);
System.out.println("Você criou uma nova sala, aperte enter para começar a partida");
reader.readLine();
// wait.cancel(true);
out.println(0x1);
return null;
}
if (msg[0].toLowerCase().equals("entrar")) {
out.println(2);
out.println(msg[1]);
try {
final var buffer_ = in.readLine();
final int n = Integer.valueOf(buffer_);
if (n == 1) {
System.out.println("Você foi aceito na sala, aguarde enquanto a partida não começa");
final int conf = Integer.valueOf(in.readLine());
if (conf == 1) {
System.out.println("Você esta na partida da room " + msg[1]);
return null;
}
else {
System.out.println("Parece que o dono da room não quer mais jogar");
System.out.println(bmsg);
}
} else {
System.out.println("Esta sala realmente existe?");
}
}
catch(Exception e) {
System.out.println(bmsg);
}
}
}
}
// out.println();
// System.out.println("Foi encontrado um adversario para você"); return null;
});
break;
case 0x2 :
doIfYourPackageID(id,
() -> {System.out.println(in.readLine()); return null;});
break;
case 0x3 :
doIfYourPackageID(id,
() -> {
final Function<String, Optional<Integer>> try_parser = (s) -> {
try {
return Optional.of(Integer.valueOf((Integer.parseInt(s))));
}
catch(Exception e) {
return Optional.empty();
}
};
System.out.println("Digite sua jogada(quantos palitos você colocará; quanto você que dará)), você tem 15 segundos para dar sua resposta");
String[] play = {null, null};
play = reader.readLine().split(";");
Callable<Boolean> checkIfOkay = () -> {
while (!in.ready()) {}
final Optional<Integer> try_ = try_parser.apply(in.readLine());
return try_.isPresent() && try_.get() == 1;
};
out.println(play[0]);
out.println(play[1]);
System.out.println("Você deve aguardar as jogada dos outros players");
return null;
});
break;
case 0x4 :
doIfYourPackageID(id,
() -> {out.println(id); return null;});
break;
default :
Thread.sleep(1);
}
}
catch(Exception e) {
// System.out.println(e);
}
}
}
).start(); //wait a response of the Server
}
else {
/// System.out.println("O servidor recusou sua entrada");
}
}
public static void main (String[] args) throws IOException, InterruptedException {
Client client = new Client();
final String name;
System.out.println("Antes de entrar, me informe seu nome!");
client.startConnection("127.0.0.1", 6666);
name = client.reader.readLine();
client.solicitEnter("Enter", name);
client.StartGame();
}
}
import java.net.*;
import java.io.*;
import java.util.LinkedList;
import java.util.ArrayList;;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.*;
import java.util.stream.Stream;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.HashMap;
public class Server {
public class Pair<T1, T2> {
Pair(T1 t1, T2 t2) {
this.t1 = t1;
this.t2 = t2;
}
T1 first() {return t1;}
T2 second() {return t2;}
void setFirst(T1 n) {
t1 = n;
}
void setSecond(T2 n) {
t2 = n;
}
T1 t1;
T2 t2;
}
public class Tuple<T, T1, T2> {
Tuple(T t0, T1 t1, T2 t2) {
this.t0 = t0;
this.t1 = t1;
this.t2 = t2;
}
T first() {return t0;}
T1 second() {return t1;}
T2 three() {return t2;}
//and so and so... :0
T t0;
T1 t1;
T2 t2;
}
public static enum Protocols_Values {
AUTHORIZED_Player(0x0),
REQUEST_ACTION(0x1),
SIMPLY_MSG(0x2),
REQUEST_PLAY(0x3),
CHECK_PING(0x4),
ANSWER_ROOM(0x4),
;
private int id;
Protocols_Values (int x) {
id = x;
}
int getProtocolID() {
return id;
}
}
public static enum authority {
ANON,GAMER;
}
public class Room {
Room(Gamer g) {
owner = g;
players = new ArrayList<Gamer>();
}
public void add_player(Gamer g1) {
players.add(g1);
}
public void set_list(ArrayList<Gamer> ls) {
players = ls;
}
ArrayList<Gamer> players;
Gamer owner;
}
public class Gamer {
Gamer(int id, String name, Tuple<Socket, BufferedReader, PrintWriter> T) {
ID = id;
conex0 = T;
this.name = name;
pontuation = 0;
last_package_time = Long.valueOf(System.nanoTime());
}
int getID() {
return ID;
}
public void incrPontuation() {
++pontuation;
}
public int getPontuation() {
return pontuation;
}
public String getName() {
return name;
}
public Tuple<Socket, BufferedReader, PrintWriter> getConnection() {
return conex0;
}
public void upgradeLastPackageTime() {
last_package_time = Long.valueOf(System.nanoTime());
}
private int ID;
private String name;
public int pontuation;
Tuple<Socket, BufferedReader, PrintWriter> conex0;
Function<Gamer, Function<Thread, Void>> onDesconnect;
public Thread gamer_process;
Long last_package_time;
Long timer;
}
class State {
State() {
gamers = new LinkedList<>();
game_g = new HashMap<>();
waiting_gamers = new LinkedList<>();
IDs = 0;
rooms = new HashMap<>();
}
State push_player(int id, Gamer T) {
gamers.add(T);
game_g.put(Integer.valueOf(id), T);
waiting_gamers.add(T);
return this;
}
State remove_player(Gamer T) {
gamers.remove(T.getID());
return this;
}
public int getID() {return IDs;}
public int pushID() {return ++IDs;}
private Queue<Gamer> gamers = new LinkedList<>();
private Queue<Gamer> waiting_gamers = new LinkedList<>();
private HashMap<Integer, Gamer> game_g;
public HashMap<Gamer, Room> rooms;
private int IDs;
}
private ServerSocket serverSocket;
private State state;
public void autorizePlayer(Gamer g,Tuple<Socket, BufferedReader, PrintWriter> T) {
(T.three()).println(Protocols_Values.AUTHORIZED_Player.getProtocolID());
(T.three()).println(g.getID());
}
public void sendAuthorization(Gamer g, int answer) {
(g.getConnection().three()).println(answer);
}
public void requestAction(Gamer g, Tuple<Socket, BufferedReader, PrintWriter> T, String y) {
(T.three()).println(Protocols_Values.REQUEST_ACTION.getProtocolID());
(T.three()).println(g.getID());
(T.three()).println(y);
}
public void sendMsg(Gamer g, String msg) {
((g.getConnection()).three()).println(Protocols_Values.SIMPLY_MSG.getProtocolID());
((g.getConnection()).three()).println(g.getID());
((g.getConnection()).three()).println(msg);
}
public void requestPing(Gamer g) {
((g.getConnection()).three()).println(Protocols_Values.CHECK_PING.getProtocolID());
((g.getConnection()).three()).println(g.getID());
}
public void requestPlayer(Gamer g) {
((g.getConnection()).three()).println(Protocols_Values.REQUEST_PLAY.getProtocolID());
((g.getConnection()).three()).println(g.getID());
}
public Boolean hasNewMsg(Gamer g) throws IOException {
return g.getConnection().second().ready();
}
public Integer getPlay(Gamer g) throws Exception {
return Integer.valueOf(Integer.parseInt(g.getConnection().second().readLine()));
}
public Gamer insert_player(Tuple<Socket, BufferedReader, PrintWriter> T, String name) {
int id = state.pushID();
Gamer _x = new Gamer(id, name, T);
state.push_player(id, _x);
autorizePlayer(_x, T);
setPlayerActivyTracking(_x);
return _x;
}
private Future<Boolean> getPlayerResponsePing(Gamer g) {
return executor.submit(() -> {
requestPing(g);
try {
return Integer.parseInt(g.getConnection().second().readLine()) == g.getID();
}
catch(Exception e) {
return false;
}
});
}
public void checkIfOn(Gamer g, Callable<Void> f, Callable<Void> f1) throws Exception { // a simulation of a *javascriptzado* function promise
final Future<Void> time_logout;
time_logout = getPlayFutureFunction(); // 10 seconds to try a new response of the client
final Future<Boolean> ping = getPlayerResponsePing(g);
while (true) {
try {
if (ping.isDone() && ping.get()) {
f.call(); return;}
if (time_logout.isDone()) {f1.call(); return;}
}
catch(Exception e) {
f1.call();
return;
}
}
}
ExecutorService executor = Executors.newCachedThreadPool(); //
// (caso o Vivas pergunte e eu posteriomente esqueça a definição pela lib)
// Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
public Future<Void> stand_by() throws IOException {
return executor.submit(() ->
{
while (true) {
Function<Socket, Void> f = (final Socket clientSocket) -> {
try {
final BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
final PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
new Thread(() -> {
try {
try_gamer(new Tuple<Socket, BufferedReader, PrintWriter>(clientSocket, in, out));
}
catch(Exception e) {
System.out.println("Trying get information of a gamer and result a unexpected expection");
}
}).start();
}
catch(Exception e) {
System.out.println("Impossible of get a output Stream");
}
return null;
};
f.apply(serverSocket.accept());
}
});
}
void backPlayerToWaiting(Gamer g) throws Exception {
checkIfOn(g, () -> {
state.waiting_gamers.add(g);
try_match_with_someone(g);
return null;
},
() -> {
sendMsg(g, "Conextion Lost, Bye :3");
System.out.println("O player " + g.getID() + " foi desconectado");
return null;
});
}
public void checkGamerIsAvaliable(Gamer g, Callable<Void> f) {
try {
f.call();
}
catch(Exception e) {
System.out.println("O player " + g.getID() + " foi desconectado");
}
}
public void make_gamer_lost(Gamer gamer1, Gamer gamer2) {
sendMsg(gamer1, "Infelizmente você perdeu tente na proxima vez :)");
sendMsg(gamer2, "Parabéns você ganhou :0 :)");
gamer2.incrPontuation();
executor.submit(() -> {
try {
sendMsg(gamer1, "Você retornará na fila em 11 segundos");
Thread.sleep(11000);
backPlayerToWaiting(gamer1);
}
catch(Exception e) {
System.out.println("Algo deu errado com o player " + gamer1.getID());
}
});
executor.submit(() -> {
try {
sendMsg(gamer2, "Você retornará na fila em 10 segundos");
Thread.sleep(10000);
backPlayerToWaiting(gamer2);
}
catch(Exception e) {
System.out.println("Algo deu errado com o player " + gamer2.getID());
}
});
}
private Future<Void> getPlayFutureFunction() {
Callable<Void> fx = (() ->
{
Thread.sleep(10*1500);
return null;
});
return executor.submit(fx);
}
private Pair<Future<Pair<Integer, Long>>, Future<Pair<Integer, Long>>> getPlayersInput(Gamer g1, Gamer g2) {
Function<Gamer, Callable<Pair<Integer, Long>>> fx = g -> (() ->
{
final Integer play = getPlay(g);
return new Pair<Integer, Long>(play, Long.valueOf(System.nanoTime()));
});
return new Pair<Future<Pair<Integer, Long>>, Future<Pair<Integer, Long>>>(executor.submit(fx.apply(g1)),
executor.submit(fx.apply(g2)));
}
<T, U> U compose(Function<T, U> f, T x) {return f.apply(x);}
public void startGame(final Gamer owner) {
final ArrayList<Gamer> players = compose((Gamer x) -> {state.rooms.get(x).players.add(x); return state.rooms.get(x).players;}, owner);
state.rooms.remove(owner);
final HashMap<Gamer, Integer> score = new HashMap<>();
final Function<String, Optional<Integer>> try_parser = (s) -> {
try {
return Optional.of(Integer.valueOf((Integer.parseInt(s))));
}
catch(Exception e) {
return Optional.empty();
}
};
players.stream().forEach((x) -> {
score.put(x, 3);
return;
});
final Function<Function<Gamer, Void>, Void> requestActionForPlayer = (f -> {
players.stream().forEach(g -> f.apply(g));
return null;
});
final HashMap<Gamer, Future<Pair<Optional<Integer>, Optional<Integer>>>> plays = new HashMap<>();
while (true) {
requestActionForPlayer.apply((x) -> {
plays.put(x, executor.submit(() -> {
requestPlayer(x);
while(true) {
if (hasNewMsg(x)) {
final Optional<Integer> toothpick = try_parser.apply(extracted().apply(x));
final Optional<Integer> guess = try_parser.apply(extracted().apply(x));
if (toothpick.isPresent() && guess.isPresent() && toothpick.get() <= score.get(x)) {
return new Pair<>(toothpick, guess);
}
}
}
}));
return null;
});
Future<Void> timer = getPlayFutureFunction();
while (!timer.isDone()) {}
final Optional<Integer> sum = plays.values().stream().map(y -> {
try {
return y.isDone() && y.get().first().isPresent() ? y.get().first().get() : Integer.valueOf(0);
}
catch (Exception e) {
return Integer.valueOf(0);
}
}).reduce((x_, y_) -> x_ + y_);
requestActionForPlayer.apply(x -> {
try {
if (plays.get(x).isDone() && plays.get(x).get().second().get() == sum.get()) {
System.out.println(plays.get(x).get().second().get() == sum.get());
score.put(x, score.get(x)-1);
sendMsg(x, "Parabens " + x.getName() + ", palpite correto");
return null;
}
sendMsg(x, "O valor era " + sum + ", tente da proxima vez :)");
return null;
}
catch(Exception e) {
return null;
}
});
final var winners = score.values().stream().anyMatch(x -> x == 0);
if (winners) {
requestActionForPlayer.apply(x -> {
if (score.get(x) == 0) {
sendMsg(x, "Parabéns você ganhou a partida :)");
} else {
sendMsg(x, "Não foi dessa vez, mas da proxima vai");
}
plays.get(x).cancel(true);
return null;
});
return;
}
}
// HashMap<Gamer, Integer> toothpicks = state.g
}
public void startMove(final Gamer gamer1, final Gamer gamer2) {
sendMsg(gamer1, "Gamer " + gamer1.getName() + ", você esta jogando com " + gamer2.getName() + " faça sua sua jogada! Você tem 10 segundos");
sendMsg(gamer2, "Gamer " + gamer2.getName() + ", você esta jogando com " + gamer1.getName() + " faça a sua jogada! Você tem 10 segundos" );
HashMap<Integer, String> plays = new HashMap<>();
plays.put(1, "pedra");
plays.put(2, "papel");
plays.put(3, "tesoura");
final Long actual_time = Long.valueOf(System.nanoTime());
executor.submit(() ->
{
final Function<Future<Pair<Integer, Long>>, Boolean> has_input = x -> x.isDone();
final Function<Function<Pair<Future<Pair<Integer, Long>>, Future<Pair<Integer, Long>>>, Future<Pair<Integer, Long>>>,
Function<Pair<Future<Pair<Integer, Long>>, Future<Pair<Integer, Long>>>, Optional<Integer>>>
getSomeGamerInput = f -> x -> {
try
{
return has_input.apply(f.apply(x)) ? Optional.of(f.apply(x).get().first()) : Optional.empty();
}
catch(Exception e) {
return Optional.empty();
}
};
final Function<Pair<Future<Pair<Integer, Long>>, Future<Pair<Integer, Long>>>,
Future<Pair<Integer, Long>>> first_lambda = x -> x.first();
final Function<Pair<Future<Pair<Integer, Long>>, Future<Pair<Integer, Long>>>,
Future<Pair<Integer, Long>>> second_lambda = x -> x.second();
Future<Void> play_time = getPlayFutureFunction();
Pair<Future<Pair<Integer, Long>>, Future<Pair<Integer, Long>>> inputs_plays = getPlayersInput(gamer1, gamer2);
Pair<Integer, Integer> pontuation = new Pair<Integer, Integer>(0, 0);
int _l=1;
Function<Integer, Void> sendRoundsForGamers = (x) -> {sendMsg(gamer1, "Rodada " + x); sendMsg(gamer2, "Rodada " + x); return null;};
sendRoundsForGamers.apply(_l);
requestPlayer(gamer1);
requestPlayer(gamer2);
Optional<Integer> player1_input;
Optional<Integer> player2_input;
while (true) {
player1_input = getSomeGamerInput.apply(first_lambda).apply(inputs_plays);
player2_input = getSomeGamerInput.apply(second_lambda).apply(inputs_plays);
if (play_time.isDone() && !player1_input.isPresent()) {
checkGamerIsAvaliable(gamer1, () -> {
sendMsg(gamer1, "Ops! Você perdeu a chance de jogar deviado ao tempo :#");
make_gamer_lost(gamer1, gamer2);
return null;
});
break;
}
if (play_time.isDone() && !player2_input.isPresent()) {
checkGamerIsAvaliable(gamer2, () -> {
sendMsg(gamer2, "Ops! Você perdeu a chance de jogar deviado ao tempo :#");
make_gamer_lost(gamer2, gamer1);
return null;
});
break;}
if (player1_input.isPresent() && player2_input.isPresent()) {
sendMsg(gamer1, "Seu adversario fez a jogada com uma " + plays.get(player2_input.get()));
sendMsg(gamer2, "Seu adversario fez a jogada com uma " + plays.get(player1_input.get()));
if (player1_input.get() - player2_input.get() == 0) {
if (inputs_plays.first().get().second() - actual_time > inputs_plays.second().get().second() - actual_time) {
pontuation.setSecond(pontuation.second()+1);
sendMsg(gamer2, "Parabéns vc ganhou pq foi mais agíl você tem agora " + pontuation.second() + " pontos");
}
else {
pontuation.setFirst(pontuation.first()+1);
sendMsg(gamer1, "Parabéns vc ganhou pq foi mais agíl você tem agora " + pontuation.first() + " pontos");
}
}
else if (player1_input.get() - player2_input.get() == -2 || player1_input.get() - player2_input.get() == 1) {
pontuation.setFirst(pontuation.first()+1);
sendMsg(gamer1, "Parabéns você esta com " + pontuation.first() + " pontos");
}
else {
pontuation.setSecond(pontuation.second()+1);
sendMsg(gamer2, "Parabéns você esta com " + pontuation.second() + " pontos");
}
if (pontuation.first() >= 3) {make_gamer_lost(gamer2, gamer1); break;}
if (pontuation.second() >= 3) {make_gamer_lost(gamer1, gamer2); break;}
sendRoundsForGamers.apply(++_l);
requestPlayer(gamer1);
requestPlayer(gamer2);
play_time = getPlayFutureFunction();
inputs_plays = getPlayersInput(gamer1, gamer2);
player1_input = getSomeGamerInput.apply(first_lambda).apply(inputs_plays);
player2_input = getSomeGamerInput.apply(second_lambda).apply(inputs_plays);
}
}
// requestPlayer(gamer1);
// requestPlayer(gamer2);
return null;
});
}
public void try_match_with_someone(Gamer t1) {
Gamer g;
sendMsg(t1, t1.getName() + ", você tem " + t1.getPontuation() + " pontos, aguarde enquanto procuramos um oponente para você jogar");
if (state.waiting_gamers.size() > 1) {
g = state.waiting_gamers.poll();
if (g != null) {
startMove(t1, g);
state.waiting_gamers.remove(t1);
}
}
}
public void setPlayerActivyTracking (Gamer g1) {
executor.submit(() -> {
try {
final Long time = (Long.valueOf(System.nanoTime()-g1.last_package_time))/Long.valueOf((long)1e+9);
if (time >= g1.timer) {
g1.onDesconnect.apply(g1).apply(Thread.currentThread());
}
Thread.sleep(4000);
setPlayerActivyTracking(g1);
}
catch(InterruptedException e) {
if (Thread.currentThread().isAlive()) {
Thread.currentThread().interrupt();
}
}
});
}
// if (option == 1) {
// final String list = state.rooms.get(gamer).players.stream().map(x -> x.getName()).reduce("Lista de jogadores on : \n", (x, y) -> {return y + " : Desafiante ativo \n" + x;});
// sendMsg(gamer, list);
// }
public void sendEffectToRoomsPlayers(Gamer owner, Consumer<Gamer> f) {
if (state.rooms.get(owner) != null) {state.rooms.get(owner).players.stream().forEach(f);}
else {}
}
public void try_gamer(Tuple<Socket, BufferedReader, PrintWriter> T) throws IOException, InterruptedException {
Function<Gamer, String> getPackage = extracted();
while (true) {
if ((T.second()).ready() && "Enter".equals((T.second()).readLine())) {
final Gamer gamer = insert_player(T, (T.second()).readLine());
System.out.println("Player " + gamer.getID() + " entrou\n");
gamer.onDesconnect = (x) -> (y) -> {
System.out.println("Player " + x.getID() + " desconectado");
y.interrupt();
gamer.gamer_process.interrupt();
state.remove_player(x);
sendEffectToRoomsPlayers(gamer, (player) -> {
sendAuthorization(gamer, 0);
return;
});
if (state.rooms.get(gamer) != null) {
state.rooms.remove(gamer);
}
return null;
};
requestAction(gamer, T,
"Você deseja criar uma sala ou entrar em uma? (Digite \"Sala;nome da sala\" para criar uma ou \"entrar\" para entrar");
gamer.gamer_process = new Thread(() -> {
while (true) {
try {
final String buffer = getPackage.apply(gamer);
final int option = Integer.parseInt(buffer);
if (option == 0x1) {
System.out.println("Player " + gamer.getName() + " criou uma nova sala");
state.rooms.put(gamer, new Room(gamer));
gamer.timer = (long) 3600;
while (true) {
final String ready_to_play = (getPackage.apply(gamer));
if (ready_to_play != null) {
sendEffectToRoomsPlayers(gamer, (player) -> {
System.out.println("Partida começou");
sendAuthorization(player, 1);
return;
});
new Thread(() -> {
startGame(gamer);
return;
}).start();
return;
}
}
}
if (option == 0x2) {
final int room_name_owner = Integer.valueOf(getPackage.apply(gamer));
if (state.game_g.get(room_name_owner) != null
&& state.rooms.get(state.game_g.get(room_name_owner)) != null) {
sendAuthorization(gamer, 1);
state.rooms.get(state.game_g.get(room_name_owner)).add_player(gamer);
sendMsg(state.game_g.get(room_name_owner), gamer.getName() + " entrou na sua room");
return;
} else {
sendAuthorization(gamer, 0);
}
}
}
catch (Exception e) {
requestAction(gamer, T,
"Algo deu errado... (Digite \"Sala;nome da sala\" para criar uma ou \"entrar\" para entrar");
}
}
});
gamer.gamer_process.start();
return;
}
}
}
private Function<Gamer, String> extracted() {
Function<Gamer, String> getPackage = x -> {
try {
final String package_ = (x.getConnection().second()).readLine();
x.upgradeLastPackageTime();
return package_;
} catch (Exception e) {
return null;
}
};
return getPackage;
}
public void init() throws IOException {
serverSocket = new ServerSocket(6666);
state = new State();
}
public static void main(String[] args) throws IOException {
Server server = new Server();
server.init();
server.stand_by();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment