Modifícame este código para que funcione igual, pero sea mas limpio ordenado, corregido de fallos y optimizado. Este codigo hace de cliente en una aplicacion en la que servidor y cliente son el nombre de las clases y se utilizan para jugar al tres en ralla(este es el cliente): package m09_uf3_tres_en_raya; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; public class Cliente { static String[][] tresEnRalla = new String[3][3]; static Scanner sc = new Scanner(System.in); public static void main(String[] args) throws SocketException, UnknownHostException, IOException { InetAddress serverAddress = InetAddress.getByName("localhost"); int serverPort = 7879; DatagramSocket socket = new DatagramSocket(); boolean partidaAcabada = false, posAbierta = true, partida = true, winner = false; String opcion; for (int i = 0; i < tresEnRalla.length; i++) { for (int j = 0; j < tresEnRalla[i].length; j++) { tresEnRalla[i][j] = "_"; } } while (!partidaAcabada) { System.out.print("[Crea una nueva partida 'puerto del juego'(numero de maximo 5 digitos)'" + "\nConnectarse a una partida" + "\nSalir\n]: "); opcion = sc.nextLine().toUpperCase(); if (opcion.equalsIgnoreCase("salir")) { System.out.println("Saliendo del programa..."); socket.close(); partidaAcabada = true; } else { if (opcion.startsWith("CREAR UNA PARTIDA NOVA ")) { opcion = "CREAR " + opcion.substring(23, opcion.length()); } else if (opcion.startsWith("CONNECTAR-SE A UNA PARTIDA")) { opcion = "UNIR-ME"; } else { opcion = "Error"; } byte[] bytesOUT = opcion.getBytes(); DatagramPacket outPacket = new DatagramPacket(bytesOUT, bytesOUT.length, serverAddress, serverPort); socket.send(outPacket); int bufferSize = 1024; int turno = (int) (Math.random() * 2 + 1); byte[] buffer = new byte[bufferSize]; DatagramPacket packet = new DatagramPacket(buffer, bufferSize); socket.receive(packet); String mensaje = new String(packet.getData(), 0, packet.getLength()).trim(); if (mensaje.equals("Actualmente no hay salas disponibles, por favor espere")) { System.out.println(mensaje); bufferSize = packet.getLength(); buffer = new byte[bufferSize]; packet = new DatagramPacket(buffer, bufferSize); socket.receive(packet); mensaje = new String(packet.getData(), 0, packet.getLength()).trim(); } if (mensaje.contains("OK ")) { String puertoSala = mensaje.substring(3, mensaje.length()); ServerSocket server = new ServerSocket(Integer.parseInt(puertoSala)); System.out.println("Sala creada, esperando jugador 2."); Socket connexio = server.accept(); DataInputStream in = new DataInputStream(connexio.getInputStream()); DataOutputStream out = new DataOutputStream(connexio.getOutputStream()); System.out.println("Cliente " + connexio.getInetAddress().getHostAddress() + " connectado."); System.out.println("Selecciona apodo"); String nicknameJ1 = sc.nextLine(); out.writeUTF(nicknameJ1); System.out.println("Hola " + nicknameJ1); String nicknameJ2 = in.readUTF(); System.out.println("Comienza el tres en raya!"); out.writeInt(turno); while (partida) { if (turno % 2 == 1) { boolean empate = comprobarEmpate(tresEnRalla); if (empate) { String resultado = tresEnRayaResultado(); System.out.println("Fin de la partida\nResultado: empate\n" + resultado); out.writeUTF("Fin de la partida\nResultado: empate\n" + resultado); partida = false; } else { while (posAbierta) { String posicion = generarTresRaya(); String[] posiciones = posicion.split("-"); try { int fila = Integer.parseInt(posiciones[0]) - 1; int columna = Integer.parseInt(posiciones[1]) - 1; if (fila >= 0 && fila <= 2 && columna >= 0 && columna <= 2) { if (tresEnRalla[fila][columna].equals("_")) { tresEnRalla[fila][columna] = "O"; posAbierta = false; } else { System.out.println("La posicion indicada no esta vacia"); } } else { System.out.println("La posicion es incorrecta"); } } catch (Exception e) { System.out.println("Las posiciones deben ser numeros enteros."); } } winner = comprobarGanador(tresEnRalla); if (winner) { System.out.println("Felicidades has ganado!\n"); String resultado = tresEnRayaResultado(); System.out.print("Resultado:\n" + resultado); out.writeUTF("Ganador " + nicknameJ2 + "\nResumen:\n" + resultado); partida = false; } else { StringBuilder sb = new StringBuilder(); for (String[] row : tresEnRalla) { for (String cell : row) { sb.append(cell).append(","); } sb.append("\n"); } String tres_en_raya_String = sb.toString(); out.writeUTF(tres_en_raya_String); } } } else { System.out.println("Turno de " + nicknameJ2 + ", por favor espera"); String mensajeEstado = in.readUTF(); String[] rows = mensajeEstado.split("\n"); tresEnRalla = new String[rows.length][]; for (int i = 0; i < rows.length; i++) { tresEnRalla[i] = rows[i].split(","); } System.out.println("Mensaje recibido:"); if (mensajeEstado.contains("Ganador ") || mensajeEstado.contains("Fin ")) { System.out.println(mensajeEstado + "\n"); partida = false; } } posAbierta = true; turno++; } in.close(); out.close(); connexio.close(); System.out.println("Conexion cerrada"); } else if (mensaje.contains(": :")) { String[] infoSala = mensaje.split(" : : "); int puertoSala = Integer.parseInt(infoSala[1]); Socket connexio = new Socket(infoSala[0], puertoSala); System.out.println("Connexion con la sala establecida."); System.out.println("Comienza el tres en raya!"); // Abrir los canales de comunicación con el cliente DataInputStream in = new DataInputStream(connexio.getInputStream()); DataOutputStream out = new DataOutputStream(connexio.getOutputStream()); System.out.println("Selecciona apodo"); String nicknameJ2 = sc.nextLine(); System.out.println("Hola " + nicknameJ2); out.writeUTF(nicknameJ2); String nicknameJ1 = in.readUTF(); turno = in.readInt(); while (partida) { if (turno % 2 == 0) { boolean empate = comprobarEmpate(tresEnRalla); if (empate) { String resultado = tresEnRayaResultado(); System.out.println("Fin de la partida\nResultado: empate\n" + resultado); out.writeUTF("Fin de la partida\nResultado: empate\n" + resultado); partida = false; } else { while (posAbierta) { String posicion = generarTresRaya(); String[] posiciones = posicion.split("-"); try { int fila = Integer.parseInt(posiciones[0]) - 1; int columna = Integer.parseInt(posiciones[1]) - 1; if (fila >= 0 && fila <= 2 && columna >= 0 && columna <= 2) { if (tresEnRalla[fila][columna].equals("_")) { tresEnRalla[fila][columna] = "X"; posAbierta = false; } else { System.out.println("La posicion indicada no esta vacia"); } } else { System.out.println("La posicion es incorrecta"); } } catch (Exception e) { System.out.println("Las posiciones deben ser numeros enteros."); } } winner = comprobarGanador(tresEnRalla); if (winner) { System.out.println("Felicidades has ganado!\n"); String resultado = tresEnRayaResultado(); System.out.print("Resultado:\n" + resultado); out.writeUTF("Ganador " + nicknameJ2 + "\nResumen:\n" + resultado); partida = false; } else { StringBuilder sb = new StringBuilder(); for (String[] row : tresEnRalla) { for (String cell : row) { sb.append(cell).append(","); } sb.append("\n"); } String csv = sb.toString(); out.writeUTF(csv); } } } else { System.out.println("Turno de " + nicknameJ1 + ", por favor espera"); String mensajeEstado = in.readUTF(); String[] rows = mensajeEstado.split("\n"); tresEnRalla = new String[rows.length][]; for (int i = 0; i < rows.length; i++) { tresEnRalla[i] = rows[i].split(","); } System.out.println("Mensaje recibido:"); if (mensajeEstado.contains("Ganador ") || mensajeEstado.contains("Fin ")) { System.out.println(mensajeEstado + "\n"); partida = false; } } posAbierta = true; turno++; } in.close(); out.close(); connexio.close(); System.out.println("Conexion cerrada"); } else { System.out.println(mensaje); } } } } public static String generarTresRaya() { System.out.println("Selecciona una posicion(ej: 1-2, 3-1): "); for (int i = 0; i < tresEnRalla.length; i++) { System.out.print(i + 1); for (int j = 0; j < tresEnRalla[i].length; j++) { System.out.print("[" + tresEnRalla[i][j] + "] "); } System.out.println(); } String posicion = sc.nextLine(); return posicion; } public static boolean comprobarGanador(String[][] tres_en_raya) { for (int i = 0; i < 3; i++) { if (!(tres_en_raya[i][0].equals("_")) && tres_en_raya[i][0].equals(tres_en_raya[i][1]) && tres_en_raya[i][0].equals(tres_en_raya[i][2])) { return true; } else if (!(tres_en_raya[0][i].equals("_")) && tres_en_raya[1][i].equals(tres_en_raya[0][i]) && tres_en_raya[2][i].equals(tres_en_raya[0][i])) { return true; } if (!(tres_en_raya[0][0].equals("_")) && tres_en_raya[0][0].equals(tres_en_raya[1][1]) && tres_en_raya[1][1].equals(tres_en_raya[2][2])) { return true; } if (!(tres_en_raya[0][2].equals("_")) && tres_en_raya[0][2].equals(tres_en_raya[1][1]) && tres_en_raya[1][1].equals(tres_en_raya[2][0])) { return true; } } return false; } public static boolean comprobarEmpate(String[][] tres_en_raya) { int celdasLlenas = 0; boolean empate = false; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (!tres_en_raya[i][j].equals("_")) { celdasLlenas++; } } } if (celdasLlenas == 9) { empate = true; } return empate; } public static String tresEnRayaResultado() { String resultado = ""; for (int i = 0; i < tresEnRalla.length; i++) { resultado += i + 1; for (int j = 0; j < tresEnRalla[i].length; j++) { resultado += "[" + tresEnRalla[i][j] + "] "; } resultado += "\n"; } return resultado; } }
package m09_uf3_tres_en_raya; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; public class Cliente { static String[][] tresEnRalla = new String[3][3]; static Scanner sc = new Scanner(System.in); public static void main(String[] args) throws SocketException, UnknownHostException, IOException { InetAddress serverAddress = InetAddress.getByName("localhost"); int serverPort = 7879; DatagramSocket socket = new DatagramSocket(); boolean partidaAcabada = false, posAbierta = true, partida = true, winner