import java.util.*; public class MasterMind { private static Scanner scanner = new Scanner(System.in); static void tirerCombinaison(MesTableaux solution, int n, int max) { for (int i = 0; i < n; i++) { solution.setValue(i,(1 + (int) (Math.random() * max))); } } static void demanderCoup(MesTableaux proposition, int n){ int b; System.out.print("Entrez les " + n + " chiffres de votre proposition"); System.out.println("(faite des espace entre chaque chiffres et terminés par un retour chariot) :"); for (int i = 0; i < n; i++) { b = scanner.nextInt(); proposition.setValue(i,b); } } static boolean compare(int n, MesTableaux combinaison1, MesTableaux combinaison2,MesTableaux reponse) { int nbMp = 0; int nbOk = 0; boolean [] marque = new boolean[n]; boolean trouve = true; for (int i = 0; i < n; i++) { if (combinaison1.getValue(i) == combinaison2.getValue(i)) { nbOk++; marque[i] = true; } else { trouve = false; marque[i] = false; } } for (int i = 0; i < n; i++) { if (combinaison1.getValue(i) != combinaison2.getValue(i)) { int j = 0; boolean trouveMalPlace = false; while ((j < n) && !trouveMalPlace) { if (!marque[j] && combinaison1.getValue(i) == combinaison2.getValue(j)) { nbMp++; marque[j] = true; trouveMalPlace = true; } j++; } } } reponse.setValue(0,nbOk); reponse.setValue(1,nbMp); return trouve; } static void afficheCombinaison(MesTableaux combinaison, int n) { for (int i = 0; i < n; i++) System.out.print(combinaison.getValue(i)); System.out.println(" "); }; static void afficheReponse(MesTableaux reponse) { for (int i = 0; i < reponse.getValue(0); i++) System.out.print('#'); for (int i = 0; i < reponse.getValue(1); i++) System.out.print('O'); System.out.println(); } static void bienvenue(int n, int max, int maxCoups) { System.out.println(" **- BIENVENUE DANS LE JEU DU MASTERMIND -**\n "); System.out.printf(" chiffres [compris entre 1 et " +max+ " avec répétitions possibles]\n"); System.out.printf(" Saurez vous là trouver en moins de " +maxCoups+ "coups ?\n"); System.out.println(" O = chiffre mal placée ; # = chiffre bien placée "); } static void mastermind(int size, int maxDigit, int maxCoups) { MesTableaux solution = new MesTableaux(size); MesTableaux proposition = new MesTableaux(size); MesTableaux reponse = new MesTableaux(2); int nbCoups = 0; boolean trouve = false; bienvenue(size, maxDigit, maxCoups); tirerCombinaison(solution, size, maxDigit); do { demanderCoup(proposition, size); nbCoups++; trouve = compare(size, solution, proposition, reponse); afficheReponse(reponse); } while (!trouve && (nbCoups < maxCoups)); if (trouve) { System.out.print("Bravo ! Vous avez trouvé le code en "); System.out.print(nbCoups); System.out.println(" coups"); } else { System.out.println("Désolé ! Vous n'avez pas trouvé le bon code ..."); System.out.println("Le bon code était : "); afficheCombinaison(solution, size); System.out.println("Au Revoir !!"); } } }