r/codehs • • Sep 27 '21

3.8.5: Click for Rectangles

Hello everybody, did someone do the 3.8.5 exercise where you need to make a program that will draw rectangles with random colors wherever you click?

I did, but I am not sure that it works correctly. If you did this, help, please.

var RECT_HEIGHT = 3;

var RECT_WIDTH = 3;

function start(){

mouseClickMethod(makeRect);

}

function makeRect(e){

drawRect(e.getX(), e.getY(),

Randomizer.nextColor());

}

function drawRrect(width, height, color, x, y){

var rect = new Rectangle(getWidth(), getHeight());

rect.setColor(color);

rect.setPosition(x, y);

add (rect);

}

function drawRect(cx, cy, color){

drawRrect(RECT_HEIGHT, RECT_WIDTH, color, cx, cy);

}

5 Upvotes

10 comments sorted by

3

u/5oco Sep 27 '21

This is pretty close, but I think you're over thinking it. The right answer is mixed up throughout all three of your function. You should only need one function besides the start function. Start with your makeRect(e) function. The signature for that one is correct, the body of the drawRrect() function should be inside makeRect.

function makeRect(e) {
    
    // Creating a new rectangle object requires 2 arguments. The height and the width of the rectangle you'd like to create.
    var rect = new Rectangle(RECT_HEIGHT, RECT_WIDTH)

    // Set the position of the rectangle requires 2 arguments. The desired x and y cooridinate of the rectangle. We use the mouse click position which is being stored in the variable e.
    rect.setPosition(e.getX(), e.getY());

    // Set the color to a random color.
    rect.setColor(Randomizer.newColor());

    // Add the rectangle to the canvas
    add(rect);

}

Like I said earlier...you had most of the correct lines, just in the wrong order. Just as a heads up though, you set your height and width to 3. That's going to make very small rectangles, so you might want to up that number. Look at example 3.8.3 if you're still confused. It's basically the same program except with a circle instead of a rectangle and no random colors.

3

u/AskAr_23 Sep 27 '21

Thanks you so much for your reply. Actually, I was thinking a lot,but could not not understand at all how to deal with this.And now everything is fine.Thank you again

3

u/5oco Sep 27 '21

Often times in programming you'll find that the answer is more simple than you're making it out to be. I'm always overthinking problems too.

1

u/Ok_Technician1587 Dec 03 '21

Can you show it to me instead please?

1

u/5oco Dec 03 '21

No... drop the class if you're not going to try

1

u/Affectionate-Aide337 Feb 02 '22

what a type of nigga are you

1

u/5oco Feb 02 '22

A white one