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:
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; //PHEIGHT and PWIDTH passed from bp
panelWidth = width;
boxH =102;
boxW =102;
}
public void add (){
this.boxH -= 2;
this.boxW -= 2; //decrease box size by 2 everytime one spawns.
int newY = (int) (Math.random()*701);
int newX = (int) (Math.random())*701; //generate a number between 0-700
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; //set new box co-ords
}
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));
}//endIf
}
Could someone tell me where I’ve gone wrong please?