package de.ulbrich.patrick; import inouthelpers.*; class Mastermind2 { static final int COLOR_RED = 0; static final int COLOR_YELLOW = 1; static final int COLOR_GREEN = 2; static final int COLOR_BLUE = 3; static final int COLOR_PINK = 4; static final int COLOR_BROWN = 5; static final int USED_SLOT = -1; static final int USED_TRY = -2; static final int NUM_SLOTS = 4; public static void main(String[] args) { int[] colors = { COLOR_RED, COLOR_YELLOW, COLOR_GREEN, COLOR_BLUE, COLOR_PINK, COLOR_BROWN }; int[] slotLayout = new int[NUM_SLOTS]; // initialize slot layout with random colors for(int i = 0; i < slotLayout.length; i++) { int idx = (int)(Math.random() * NUM_SLOTS); slotLayout[i] = colors[idx]; } int tries[] = new int[NUM_SLOTS]; int nLoops = 0; int nMatchingTries; /* slotLayout = new int[] { 0, 3, 0 ,2 }; // remove me */ do { int[] slots = new int[NUM_SLOTS]; // (re)store intitial slot layout for(int i = 0; i < slotLayout.length; i++) slots[i] = slotLayout[i]; nMatchingTries = 0; Out.println("Rot = 0, gelb = 1, gruen = 2, blau = 3, pink = 4, braun = 5"); Out.print("Bitte Zahlen durch Leerzeichen getrennt eingeben: "); // read in user tries for (int i = 0; i < tries.length; i++) tries[i] = In.readInt(); Out.print("Wertung: "); // determine perfectly matching user tries (both, color AND position do match) (output black indication) for(int i = 0; i < tries.length; i++) { if (tries[i] == slots[i]) { Out.print("Schwarz "); tries[i] = USED_TRY; slots[i] = USED_SLOT; nMatchingTries++; } } if (nMatchingTries < NUM_SLOTS) { // determine user tries that indeed match by color, but not by position (output white indication) // loop through user tries for(int i = 0; i < tries.length; i++) { // loop through slots for(int j = 0; j < slots.length; j++) { // compare each user try against all slots, // skip slots that have already been tested in the preceding loop if (tries[i] == slots[j] && i != j) { Out.print("Weiss "); slots[j] = USED_SLOT; break; // exit slot loop } } } } Out.println(); nLoops++; } while (nMatchingTries < NUM_SLOTS); Out.println("Glückwunsch: Erraten nach " + nLoops + " Runden."); Out.print("Lösungsmuster: "); for(int i = 0; i < slotLayout.length; i++) { switch(slotLayout[i]) { case COLOR_RED: Out.print("Rot (" + COLOR_RED + ") "); break; case COLOR_YELLOW: Out.print("Gelb (" + COLOR_YELLOW + ") "); break; case COLOR_GREEN: Out.print("Grün (" + COLOR_GREEN + ") "); break; case COLOR_BLUE: Out.print("Blau (" + COLOR_BLUE + ") "); break; case COLOR_PINK: Out.print("Pink (" + COLOR_PINK + ") "); break; case COLOR_BROWN: Out.print("Braun (" + COLOR_BROWN + ") "); break; } } } }