package colours; import java.awt.Color; public class TwentyFour implements Colour { private int red,green,blue; public TwentyFour() { this(255,255,255); } public TwentyFour(int r, int g, int b) { initialize(r,g,b); } public TwentyFour(String c) { int integerNumber; int r,g,b; try { integerNumber=Integer.parseInt(c,16); r=(integerNumber&0xFF0000)>>16; g=(integerNumber&0x00FF00)>>8; b=(integerNumber&0x0000FF); initialize(r,g,b); } catch (NumberFormatException nfe) { throw new InvalidColourException(); } } public TwentyFour(Color c) { this(c.getRed(),c.getGreen(),c.getBlue()); } private void initialize(int r, int g, int b) { if ((r<0)|(r>255)|(g<0)|(g>255)|(b<0)|(b>255)) throw new InvalidColourException(); red=r; green=g; blue=b; } public double getRed() { return red/255.0; } public double getGreen() { return green/255.0; } public double getBlue() { return blue/255.0; } public double getCyan(){ return 1.0-getRed(); } public double getMagenta(){ return 1.0-getGreen(); } public double getYellow(){ return 1.0-getBlue(); } //Mixes another Colour with this one, to produce a new one. //"Mixing" is calculated by averaging the reds, greens, and blues public Colour mix(Colour c) { int r=(int)(255*(c.getRed()+getRed())/2); int g=(int)(255*(c.getGreen()+getGreen())/2); int b=(int)(255*(c.getBlue()+getBlue())/2); return new TwentyFour(r,g,b); } public Colour lighten() { int r=(255+red)/2; int g=(255+green)/2; int b=(255+blue)/2; return new TwentyFour(r,g,b); } public Colour darken() { return new TwentyFour(red/2,green/2,blue/2); } public Colour invert() { return new TwentyFour(255-red,255-green,255-blue); } public Colour grey() { double luminosity=(getRed()+getGreen()+getBlue())/3.0; int g=(int)(255*luminosity); return new TwentyFour(g,g,g); } //Any Colour should be String-ily expressed in 24-bit hexadecimal notation, irrespective of implementation public String toString() { String rs=Integer.toString(red,16),gs=Integer.toString(green,16),bs=Integer.toString(blue,16); return (rs.length()==1?"0"+rs:rs)+(gs.length()==1?"0"+gs:gs)+(bs.length()==1?"0"+bs:bs); } //Represent this colour as a java.awt.Color //Note: Do NOT use this function for any of the other methods you implement! (including mixing) public Color speltPoorly() { return new Color((float)getRed(),(float)getGreen(),(float)getBlue()); } }