Jump to content

Forcing a square to fin on a grid (JAVA)

CreepyPro

The method is supposed to draw a square on a 10x10 grid using the length and x,y coordinate an user inputs and adjust the length in case the square doesn't fit. I'm having trouble figuring out the math for adjusting the length to fit the grid.

For example, if the user inputs (x-7, y-2, length-4) my square goes out of the grid by 1.

 

public static void drawSquare(int x, int y, int len) {
        if(x+len>10)
            len = Math.max(x, len)-Math.min(x, len);
        if(y+len>10)
            len = Math.max(y, len)-Math.min(y, len);
        System.out.println("side length = " + len + ", area = " + len*len);
        drawLine(x, y, x+len, y);
        drawLine(x+len,y,x+len,y-len);
        drawLine(x+len, y-len, x, y-len);
        drawLine(x, y-len, x, y);
    }

 

trjrj.PNG

Link to comment
Share on other sites

Link to post
Share on other sites

You are not clearly testing for any boundary conditions.

 

You could maybe compute each corner and check it's within bounds.

 

You could work off a central point of the shape. Doing this means the edge points would be a certain distance, from that central point, on each axis.

 

Should you even try to draw anything if it is outside the bounds?

 

Just some ideas and thoughts for you.

 

If you're interested in a product please download and read the manual first.

Don't forget to tag or quote in your reply if you want me to know you've answered or have another question.

Link to comment
Share on other sites

Link to post
Share on other sites

You max condition is not good at all. Should be something like :

public static void drawSquare(int x, int y, int len) {
        if(x+len>10)
            len = 10-x;
        if(y+len>10)
            len = 10-y; 
        System.out.println("side length = " + len + ", area = " + len*len);
        drawLine(x, y, x+len, y);
        drawLine(x+len,y,x+len,y-len);
        drawLine(x+len, y-len, x, y-len);
        drawLine(x, y-len, x, y);
    }

Possibly need an extra -1 to each but that will depend if you grid starts at index 0 or index 1

Link to comment
Share on other sites

Link to post
Share on other sites

i dont know if you programm java gui like u programm android layout

if so just wrap it in any kind of component and make that component fill_parent

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×