| 1 | import java.awt.Color; |
| 2 | import java.util.Arrays; |
| 3 | |
| 4 | public class Eye { |
| 5 | private String strColor; |
| 6 | private Color color; |
| 7 | private String[] colorsList = {"black", "blue", "brown", "green"}; |
| 8 | |
| 9 | Eye() { |
| 10 | //this.color = Color.white; |
| 11 | sortColorList(); |
| 12 | } |
| 13 | |
| 14 | /** |
| 15 | * @param color |
| 16 | */ |
| 17 | Eye(String color) { |
| 18 | setStrColor(color); |
| 19 | setColor(color); |
| 20 | sortColorList(); |
| 21 | } |
| 22 | |
| 23 | public String getStrColor() { |
| 24 | return strColor; |
| 25 | } |
| 26 | |
| 27 | public void setStrColor(String strColor) { |
| 28 | if (validateColor(strColor)) { |
| 29 | this.strColor = strColor; |
| 30 | } else { |
| 31 | throw new IllegalArgumentException("Color must be" + this.colorListToString()); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | public String[] getColorsList() { |
| 36 | return colorsList; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * @return |
| 41 | */ |
| 42 | public Color getColor() { |
| 43 | return color; |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * @param color |
| 48 | */ |
| 49 | public void setColor(String color) { |
| 50 | if (validateColor(color)) { |
| 51 | if (color.equals("black")) |
| 52 | this.color = Color.black; |
| 53 | else if (color.equals("blue")) |
| 54 | this.color = Color.blue; |
| 55 | else if (color.equals("brown")) |
| 56 | this.color = new Color(88, 41, 0); |
| 57 | else if (color.equals("green")) |
| 58 | this.color = Color.green; |
| 59 | } else { |
| 60 | throw new IllegalArgumentException("Color must be" + this.colorListToString()); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * @param color |
| 66 | * @return |
| 67 | */ |
| 68 | private boolean validateColor(String color) { |
| 69 | for (String c : colorsList) { |
| 70 | if (color.equals(c)) { |
| 71 | return true; |
| 72 | } |
| 73 | } |
| 74 | return false; |
| 75 | } |
| 76 | |
| 77 | private void sortColorList() { |
| 78 | Arrays.sort(this.colorsList); |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * @param eye |
| 83 | * @return |
| 84 | */ |
| 85 | public int distanceTo(Eye eye) { |
| 86 | double r_diff = this.getColor().getRed() - eye.getColor().getRed(); |
| 87 | double g_diff = this.getColor().getGreen() - eye.getColor().getGreen(); |
| 88 | double b_diff = this.getColor().getBlue() - eye.getColor().getBlue(); |
| 89 | //See https://en.wikipedia.org/wiki/Color_difference |
| 90 | Double distance = Math.sqrt(2 * Math.pow(r_diff, 2) + 4 * Math.pow(g_diff, 2) + 3 * Math.pow(b_diff, 2)); |
| 91 | return distance.intValue(); |
| 92 | } |
| 93 | |
| 94 | private String colorListToString() { |
| 95 | StringBuilder stringBuilder = new StringBuilder(); |
| 96 | for (String c : colorsList) { |
| 97 | stringBuilder.append(" "); |
| 98 | stringBuilder.append(c); |
| 99 | } |
| 100 | return stringBuilder.toString(); |
| 101 | } |
| 102 | } |