0

Hey if i have a simple rectangle class, how can i make it so that it creates that rectangle next to each other in a grid like pattern? maybe like 10 rows 10 columns?

public class Vak {

private int posX = 0;
private int posY = 0;
private int width = 50;
private int height = 50;
private Color colour;


public Vak(Color c, int x, int y){
    this.colour = c;
    this.posX = x;
    this.posY = y;

}

public int vakPosY(){
    return this.posY;
}
public int vakPosX(){
    return this.posX;
}

public void draw (Graphics g){
    g.setColor(this.colour);

    g.drawRect(posX, posY, width, height);
}

public void move(int numberPixelsX, int numberPixelsY){
    this.posX = this.posX + numberPixelsX;
    this.posY = this.posY + numberPixelsY;
}

}

this is my code for rectangle "vak"

1 Answers1

1

Is this what you are looking for?

int mapWidth = 10;
int mapHeight = 10;
// tileWidth and tileHeight should probably be public static const fields or static readonly properties of some class, but I put them here for now.
int tileWidth = 50;  // Pixels
int tileHeight = 50;  // Pixels
// tiles should probably be a field of a Map class (if you have one)
Vak[][] tiles = new Vak[mapWidth][mapHeight];
for(int x = 0; x < mapWidth; x++)
{
    for(int y = 0; y < mapHeight; y++)
    {
        tiles[x][y] = new Vak(Color.white, x*tileWidth, y*tileHeight);
    }
}

And then in the drawing part of the main loop:

for(Vak[] row : tiles)
{
    for(Vak tile : row)
    {
        tile.draw(g);
    }
}