4 files + 377 − 0 Inline Compare changes Side-by-side Inline Show whitespace changes Files 4 src/Client.java 0 → 100644 +93 −0 Original line number Diff line number Diff line package src; import java.io.*; import java.net.*; import java.util.Scanner; public class Client { private static final String SERVER_ADDRESS = "localhost"; private static final int PORT = 1234; private Socket socket; private BufferedReader in; private PrintWriter out; private Scanner scanner; public Client() { scanner = new Scanner(System.in); } public void connect() { try { socket = new Socket(SERVER_ADDRESS, PORT); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); System.out.println("Connecté au serveur Mastermind !"); play(); } catch (IOException e) { System.err.println("Erreur de connexion au serveur : " + e.getMessage()); } finally { closeConnection(); } } private void play() { while (true) { String guess = getUserInput(); if (guess == null) continue; sendGuess(guess); String response = receiveResponse(); if (response == null) { System.out.println("Connexion fermée par le serveur."); break; } System.out.println("Réponse du serveur : " + response); if (response.contains("Félicitations")) { System.out.println("Félicitations ! Vous avez trouvé la bonne combinaison !"); break; } } } private String getUserInput() { System.out.print("Entrez une combinaison (4 lettres parmi B,G,O,R,W,Y) : "); String input = scanner.nextLine().toUpperCase(); if (!input.matches("[BGORWY]{4}")) { System.out.println("Combinaison invalide, veuillez entrer exactement 4 lettres parmi B, G, O, R, W, Y."); return null; } return input; } private void sendGuess(String guess) { out.println(guess); } private String receiveResponse() { try { return in.readLine(); } catch (IOException e) { System.err.println("Erreur de lecture du serveur : " + e.getMessage()); return null; } } private void closeConnection() { try { if (socket != null) socket.close(); if (in != null) in.close(); if (out != null) out.close(); scanner.close(); } catch (IOException e) { System.err.println("Erreur lors de la fermeture des ressources : " + e.getMessage()); } } public static void main(String[] args) { new Client().connect(); } } src/Client2.java 0 → 100644 +93 −0 Original line number Diff line number Diff line package src; import java.io.*; import java.net.*; import java.util.Scanner; public class Client2 { private static final String SERVER_ADDRESS = "localhost"; private static final int PORT = 1234; private Socket socket; private BufferedReader in; private PrintWriter out; private Scanner scanner; public Client2() { scanner = new Scanner(System.in); } public void connect() { try { socket = new Socket(SERVER_ADDRESS, PORT); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); System.out.println("Connecté au serveur Mastermind !"); play(); } catch (IOException e) { System.err.println("Erreur de connexion au serveur : " + e.getMessage()); } finally { closeConnection(); } } private void play() { while (true) { String guess = getUserInput(); if (guess == null) continue; sendGuess(guess); String response = receiveResponse(); if (response == null) { System.out.println("Connexion fermée par le serveur."); break; } System.out.println("Réponse du serveur : " + response); if (response.contains("Félicitations")) { System.out.println("Félicitations ! Vous avez trouvé la bonne combinaison !"); break; } } } private String getUserInput() { System.out.print("Entrez une combinaison (4 lettres parmi B,G,O,R,W,Y) : "); String input = scanner.nextLine().toUpperCase(); if (!input.matches("[BGORWY]{4}")) { System.out.println("Combinaison invalide, veuillez entrer exactement 4 lettres parmi B, G, O, R, W, Y."); return null; } return input; } private void sendGuess(String guess) { out.println(guess); } private String receiveResponse() { try { return in.readLine(); } catch (IOException e) { System.err.println("Erreur de lecture du serveur : " + e.getMessage()); return null; } } private void closeConnection() { try { if (socket != null) socket.close(); if (in != null) in.close(); if (out != null) out.close(); scanner.close(); } catch (IOException e) { System.err.println("Erreur lors de la fermeture des ressources : " + e.getMessage()); } } public static void main(String[] args) { new Client2().connect(); } } src/Code.java 0 → 100644 +78 −0 Original line number Diff line number Diff line package src; import java.util.Random; public class Code { public static final int CODE_LENGTH = 4; public static char[] COLORS = new char[]{'B','G','O','R','W','Y'}; private final char[] codeWord = new char[CODE_LENGTH]; public Code(Random random){ for (int i = 0; i < CODE_LENGTH; i++) { codeWord[i] = COLORS[random.nextInt(COLORS.length)]; } } public Code(String codeString){ assert(codeString.length() == CODE_LENGTH); for(int i=0; i<CODE_LENGTH; i++) codeWord[i] = codeString.charAt(i); } @Override public String toString() { return new String(codeWord); } /** * return the number of colors of guess that are correctly positioned */ public int numberOfColorsWithCorrectPosition(Code guess){ int count = 0; for(char color : COLORS){ count += numberOfMatches(color, guess); } return count; } /** * return the number of colors of guess that are in this codeWord * but do not have the correct position */ public int numberOfColorsWithIncorrectPosition(Code guess){ int count = 0; for(char color:COLORS){ int nMatchedOccurrences = numberOfMatches(color, guess); int nUnmatchedOccurrencesCode = numberOfOccurrences(color, this) - nMatchedOccurrences; int nUnmatchedOccurrencesGuess = numberOfOccurrences(color, guess) - nMatchedOccurrences; count += Math.min(nUnmatchedOccurrencesCode, nUnmatchedOccurrencesGuess); } return count; } private int numberOfOccurrences(char color, Code code){ int count = 0; for (int i = 0; i < CODE_LENGTH; i++) { if (code.codeWord[i] == color) count++; } return count; } private int numberOfMatches(char color, Code guess){ int count = 0; for (int i = 0; i < CODE_LENGTH; i++) { if ((this.codeWord[i] == guess.codeWord[i]) && (this.codeWord[i] == color)){ count++; } } return count; } @Override public boolean equals(Object o){ if (o == null) return false; if (!(o instanceof Code)) return false; return this.toString().equals(o.toString()); } } src/Server.java 0 → 100644 +113 −0 Original line number Diff line number Diff line package src; import java.io.*; import java.net.*; import java.util.Random; public class Server { private static final int PORT = 1234; private static final int CODE_LENGTH = 4; private Code secretCode; public Server() { this.secretCode = generateSecretCode(); System.out.println("Code secret généré : " + secretCode); } private Code generateSecretCode() { Random random = new Random(); return new Code(random); // Génère un code secret aléatoire } public void start() { try (ServerSocket serverSocket = new ServerSocket(PORT)) { System.out.println("Serveur en attente de connexions sur le port " + PORT + "..."); // Serveur qui accepte plusieurs clients simultanément while (true) { try { // Accepte un client et lui attribue un thread pour gérer la communication Socket clientSocket = serverSocket.accept(); System.out.println("Client connecté !"); new Thread(new ClientHandler(clientSocket)).start(); } catch (IOException e) { System.err.println("Erreur lors de l'acceptation d'un client : " + e.getMessage()); } } } catch (IOException e) { System.err.println("Erreur lors du démarrage du serveur : " + e.getMessage()); } } // Classe pour gérer un client dans un thread séparé private class ClientHandler implements Runnable { private Socket clientSocket; private BufferedReader in; private PrintWriter out; public ClientHandler(Socket socket) { this.clientSocket = socket; try { this.in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); this.out = new PrintWriter(clientSocket.getOutputStream(), true); } catch (IOException e) { System.err.println("Erreur lors de la création des flux d'entrée/sortie : " + e.getMessage()); } } @Override public void run() { try { String input; int attempts = 0; // Interaction avec le client while ((input = in.readLine()) != null) { attempts++; System.out.println("Tentative " + attempts + " du client : " + input); // Vérifier si la combinaison est valide if (input.length() != CODE_LENGTH || !input.matches("[BGORWY]{4}")) { out.println("Erreur : Entrée invalide. Essayez encore."); continue; } // Créer une instance de Code à partir de l'entrée du client Code guess = new Code(input); int correctPosition = secretCode.numberOfColorsWithCorrectPosition(guess); int incorrectPosition = secretCode.numberOfColorsWithIncorrectPosition(guess); // Envoyer le résultat au client out.println(correctPosition + " " + incorrectPosition); // Vérifier si le client a trouvé la bonne combinaison if (correctPosition == CODE_LENGTH) { System.out.println("Le client a trouvé la combinaison " + secretCode + " en " + attempts + " essais."); out.println("Félicitations ! Vous avez trouvé la bonne combinaison !"); break; } } } catch (IOException e) { System.err.println("Erreur de communication avec le client : " + e.getMessage()); } finally { closeConnection(); } } // Fermeture propre des ressources private void closeConnection() { try { if (clientSocket != null) clientSocket.close(); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { System.err.println("Erreur lors de la fermeture de la connexion : " + e.getMessage()); } } } public static void main(String[] args) { Server server = new Server(); server.start(); } }
src/Client.java 0 → 100644 +93 −0 Original line number Diff line number Diff line package src; import java.io.*; import java.net.*; import java.util.Scanner; public class Client { private static final String SERVER_ADDRESS = "localhost"; private static final int PORT = 1234; private Socket socket; private BufferedReader in; private PrintWriter out; private Scanner scanner; public Client() { scanner = new Scanner(System.in); } public void connect() { try { socket = new Socket(SERVER_ADDRESS, PORT); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); System.out.println("Connecté au serveur Mastermind !"); play(); } catch (IOException e) { System.err.println("Erreur de connexion au serveur : " + e.getMessage()); } finally { closeConnection(); } } private void play() { while (true) { String guess = getUserInput(); if (guess == null) continue; sendGuess(guess); String response = receiveResponse(); if (response == null) { System.out.println("Connexion fermée par le serveur."); break; } System.out.println("Réponse du serveur : " + response); if (response.contains("Félicitations")) { System.out.println("Félicitations ! Vous avez trouvé la bonne combinaison !"); break; } } } private String getUserInput() { System.out.print("Entrez une combinaison (4 lettres parmi B,G,O,R,W,Y) : "); String input = scanner.nextLine().toUpperCase(); if (!input.matches("[BGORWY]{4}")) { System.out.println("Combinaison invalide, veuillez entrer exactement 4 lettres parmi B, G, O, R, W, Y."); return null; } return input; } private void sendGuess(String guess) { out.println(guess); } private String receiveResponse() { try { return in.readLine(); } catch (IOException e) { System.err.println("Erreur de lecture du serveur : " + e.getMessage()); return null; } } private void closeConnection() { try { if (socket != null) socket.close(); if (in != null) in.close(); if (out != null) out.close(); scanner.close(); } catch (IOException e) { System.err.println("Erreur lors de la fermeture des ressources : " + e.getMessage()); } } public static void main(String[] args) { new Client().connect(); } }
src/Client2.java 0 → 100644 +93 −0 Original line number Diff line number Diff line package src; import java.io.*; import java.net.*; import java.util.Scanner; public class Client2 { private static final String SERVER_ADDRESS = "localhost"; private static final int PORT = 1234; private Socket socket; private BufferedReader in; private PrintWriter out; private Scanner scanner; public Client2() { scanner = new Scanner(System.in); } public void connect() { try { socket = new Socket(SERVER_ADDRESS, PORT); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); System.out.println("Connecté au serveur Mastermind !"); play(); } catch (IOException e) { System.err.println("Erreur de connexion au serveur : " + e.getMessage()); } finally { closeConnection(); } } private void play() { while (true) { String guess = getUserInput(); if (guess == null) continue; sendGuess(guess); String response = receiveResponse(); if (response == null) { System.out.println("Connexion fermée par le serveur."); break; } System.out.println("Réponse du serveur : " + response); if (response.contains("Félicitations")) { System.out.println("Félicitations ! Vous avez trouvé la bonne combinaison !"); break; } } } private String getUserInput() { System.out.print("Entrez une combinaison (4 lettres parmi B,G,O,R,W,Y) : "); String input = scanner.nextLine().toUpperCase(); if (!input.matches("[BGORWY]{4}")) { System.out.println("Combinaison invalide, veuillez entrer exactement 4 lettres parmi B, G, O, R, W, Y."); return null; } return input; } private void sendGuess(String guess) { out.println(guess); } private String receiveResponse() { try { return in.readLine(); } catch (IOException e) { System.err.println("Erreur de lecture du serveur : " + e.getMessage()); return null; } } private void closeConnection() { try { if (socket != null) socket.close(); if (in != null) in.close(); if (out != null) out.close(); scanner.close(); } catch (IOException e) { System.err.println("Erreur lors de la fermeture des ressources : " + e.getMessage()); } } public static void main(String[] args) { new Client2().connect(); } }
src/Code.java 0 → 100644 +78 −0 Original line number Diff line number Diff line package src; import java.util.Random; public class Code { public static final int CODE_LENGTH = 4; public static char[] COLORS = new char[]{'B','G','O','R','W','Y'}; private final char[] codeWord = new char[CODE_LENGTH]; public Code(Random random){ for (int i = 0; i < CODE_LENGTH; i++) { codeWord[i] = COLORS[random.nextInt(COLORS.length)]; } } public Code(String codeString){ assert(codeString.length() == CODE_LENGTH); for(int i=0; i<CODE_LENGTH; i++) codeWord[i] = codeString.charAt(i); } @Override public String toString() { return new String(codeWord); } /** * return the number of colors of guess that are correctly positioned */ public int numberOfColorsWithCorrectPosition(Code guess){ int count = 0; for(char color : COLORS){ count += numberOfMatches(color, guess); } return count; } /** * return the number of colors of guess that are in this codeWord * but do not have the correct position */ public int numberOfColorsWithIncorrectPosition(Code guess){ int count = 0; for(char color:COLORS){ int nMatchedOccurrences = numberOfMatches(color, guess); int nUnmatchedOccurrencesCode = numberOfOccurrences(color, this) - nMatchedOccurrences; int nUnmatchedOccurrencesGuess = numberOfOccurrences(color, guess) - nMatchedOccurrences; count += Math.min(nUnmatchedOccurrencesCode, nUnmatchedOccurrencesGuess); } return count; } private int numberOfOccurrences(char color, Code code){ int count = 0; for (int i = 0; i < CODE_LENGTH; i++) { if (code.codeWord[i] == color) count++; } return count; } private int numberOfMatches(char color, Code guess){ int count = 0; for (int i = 0; i < CODE_LENGTH; i++) { if ((this.codeWord[i] == guess.codeWord[i]) && (this.codeWord[i] == color)){ count++; } } return count; } @Override public boolean equals(Object o){ if (o == null) return false; if (!(o instanceof Code)) return false; return this.toString().equals(o.toString()); } }
src/Server.java 0 → 100644 +113 −0 Original line number Diff line number Diff line package src; import java.io.*; import java.net.*; import java.util.Random; public class Server { private static final int PORT = 1234; private static final int CODE_LENGTH = 4; private Code secretCode; public Server() { this.secretCode = generateSecretCode(); System.out.println("Code secret généré : " + secretCode); } private Code generateSecretCode() { Random random = new Random(); return new Code(random); // Génère un code secret aléatoire } public void start() { try (ServerSocket serverSocket = new ServerSocket(PORT)) { System.out.println("Serveur en attente de connexions sur le port " + PORT + "..."); // Serveur qui accepte plusieurs clients simultanément while (true) { try { // Accepte un client et lui attribue un thread pour gérer la communication Socket clientSocket = serverSocket.accept(); System.out.println("Client connecté !"); new Thread(new ClientHandler(clientSocket)).start(); } catch (IOException e) { System.err.println("Erreur lors de l'acceptation d'un client : " + e.getMessage()); } } } catch (IOException e) { System.err.println("Erreur lors du démarrage du serveur : " + e.getMessage()); } } // Classe pour gérer un client dans un thread séparé private class ClientHandler implements Runnable { private Socket clientSocket; private BufferedReader in; private PrintWriter out; public ClientHandler(Socket socket) { this.clientSocket = socket; try { this.in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); this.out = new PrintWriter(clientSocket.getOutputStream(), true); } catch (IOException e) { System.err.println("Erreur lors de la création des flux d'entrée/sortie : " + e.getMessage()); } } @Override public void run() { try { String input; int attempts = 0; // Interaction avec le client while ((input = in.readLine()) != null) { attempts++; System.out.println("Tentative " + attempts + " du client : " + input); // Vérifier si la combinaison est valide if (input.length() != CODE_LENGTH || !input.matches("[BGORWY]{4}")) { out.println("Erreur : Entrée invalide. Essayez encore."); continue; } // Créer une instance de Code à partir de l'entrée du client Code guess = new Code(input); int correctPosition = secretCode.numberOfColorsWithCorrectPosition(guess); int incorrectPosition = secretCode.numberOfColorsWithIncorrectPosition(guess); // Envoyer le résultat au client out.println(correctPosition + " " + incorrectPosition); // Vérifier si le client a trouvé la bonne combinaison if (correctPosition == CODE_LENGTH) { System.out.println("Le client a trouvé la combinaison " + secretCode + " en " + attempts + " essais."); out.println("Félicitations ! Vous avez trouvé la bonne combinaison !"); break; } } } catch (IOException e) { System.err.println("Erreur de communication avec le client : " + e.getMessage()); } finally { closeConnection(); } } // Fermeture propre des ressources private void closeConnection() { try { if (clientSocket != null) clientSocket.close(); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { System.err.println("Erreur lors de la fermeture de la connexion : " + e.getMessage()); } } } public static void main(String[] args) { Server server = new Server(); server.start(); } }