Ok so I've finally got my BoxCatcher app working (or so I thought). The idea is that a box object is created and is drawn to the canvas, a mouseListener is set up and when the user clicks the co-ords of the click is checked against the co-ords of the box. If the click is within the box, the score is incremented by one, the box is made 2 pixels smaller and is drawn elsewhere.
The issue is that the box only changes its position on the Y axis, it always stays on at 0 on the X axis no matter how many new boxes are drawn, here's the code for Box:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public class Box { public final int panelHeight; public final int panelWidth; public int boxH; public int boxW; public int boxX; public int boxY;
public Box (int height, int width) { panelHeight = height; panelWidth = width; boxH =102; boxW =102; } public void add (){ this.boxH -= 2; this.boxW -= 2; int newY = (int) (Math.random()*701); int newX = (int) (Math.random())*701; if (panelHeight - (newY + this.boxH)< 0) { newY = panelHeight - this.boxH;} if (panelWidth - (newX + this.boxW)< 0) { newX = panelWidth - this.boxW;} this.boxY = newY; this.boxX = newX; }
public void draw ( Graphics g){ g.setColor (Color.blue); g.fillRect(boxX, boxY, boxW, boxH); }
public boolean hitTarget (int x, int y) { return((x>= this.boxX)&&(x<= (this.boxX +this.boxW))&& (y>= this.boxY)&&(y<=this.boxY + this.boxH));
} } |
Could someone tell me where I've gone wrong please?