Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

How does this create a rectangle?

The code below shows how the person created a rectangle but it never uses any numbers, yet one just appears on the screen?

package com.jamescho.game.model;

import java.awt.Rectangle;

import com.jamescho.framework.util.RandomNumberGenerator;
import com.jamescho.game.main.GameMain;
import com.jamescho.game.main.Resources;

public class Ball {

    private int x, y, width, height, velX, velY;
    private Rectangle rect;

    public Ball(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        velX = 5;
        velY = RandomNumberGenerator.getRandIntBetween(-4, 5);
        rect = new Rectangle(x, y, width, height);
    }

    public void update() {
        x += velX;
        y += velY;
        correctYCollisions();
        updateRect();
    }

    private void correctYCollisions() {
        if (y < 0) {
            y = 0;
        } else if (y + height > GameMain.GAME_HEIGHT) {
            y = GameMain.GAME_HEIGHT - height;
        } else {
            return;
        }
        velY = -velY;
        Resources.bounce.play();
    }

    private void updateRect() {
        rect.setBounds(x, y, width, height);
    }

    public void onCollideWith(Paddle p) {
        if (x < GameMain.GAME_WIDTH / 2) {
            x = p.getX() + p.getWidth();
        } else {
            x = p.getX() - width;
        }
        velX = -velX;
        velY += RandomNumberGenerator.getRandIntBetween(-2, 3);
    }

    public boolean isDead() {
        return (x < 0 || x + width > GameMain.GAME_WIDTH);
    }

    public void reset() {
        x = 300;
        y = 200;
        velX = 5;
        velY = RandomNumberGenerator.getRandIntBetween(-4, 5);
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public Rectangle getRect() {
        return rect;
    }
}

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

This line here...

import java.awt.Rectangle;

...is talking about the Rectangle class in the awt package.

I see. I ended up drawing it in a PlayState class that I created. Thanks Craig.