-2

I've seen someone do it in a video but never understood how to make an array of blocks instead of coding each block itself. please explain how i can make rows and columns of blocks. i already can draw them but cannot draw multiple ones. if you can, explain how to add layers of blocks from my block class.

To make a block i made a block class wich image is a block of dirt. then it has a method returning a new rectangle called getbounds. i use g2d.drawImage(block.getImage(), block.x, block.y, null); tto draw one block, but what can i do for multiple ones?

JayManHall
  • 11
  • 1
  • 4
  • 1
    Could you edit your question to show us how you draw a single block right now? – chessofnerd Apr 06 '14 at 03:16
  • Usually, what's done is to separate the information about locations of blocks from the logic that paints a block at a particular location. Then just loop through your table of blocks and call the paintBlockAtThisLocation subroutine for each one of them. – keshlam Apr 06 '14 at 03:27
  • @keshlam thanks i'll try that but can you still give an example. – JayManHall Apr 06 '14 at 03:30
  • [this answer](http://stackoverflow.com/a/22507549/2587435) might be of interest to you. – Paul Samsotha Apr 06 '14 at 05:42
  • Possibly related examples [here](http://stackoverflow.com/q/11553461/230513). – trashgod Apr 06 '14 at 06:07

1 Answers1

0

The following untested code should help. You will have to set 'observer' to an appropriate value. If you can't set 'observer' correctly, trying guessing the height and width of your image.

ImageObserver observer = _appropriate_value_here_;
Image image = block.getImage();
int BLOCK_X_DIM = image.getHeight(observer);   // The height of a block
int BLOCK_Y_DIM = image.getWidth(observer);    // The width of a block
for(int i = 0; i < 5; i++) {
    for(int j = 0; j < 5; j++) {
        g2d.drawImage(image, BLOCK_X_DIM * i, BLOCK_Y_DIM * j, null);
    }
}

Happy coding!

chessofnerd
  • 1,219
  • 1
  • 20
  • 40
  • Thank you very much and i love the Happy coding at the end :D. I've needed to know how to use for loops for a while and this was great! – JayManHall Apr 06 '14 at 05:00
  • Sadly, I don't know. In fact, I've never used them myself. Every time I come across a new object or class I haven't encountered (this is VERY common), I try to Google it and look up the documentation. If you are new to programming, I really recommend doing that ALWAYS! The documentation for the ImageObserver is at http://docs.oracle.com/javase/8/docs/api/java/awt/image/ImageObserver.html. Also, see [this](http://docs.oracle.com/javase/tutorial/2d/images/drawimage.html) page. It looks like the observer can be null if your Image is of type 'BufferedImage' – chessofnerd Apr 06 '14 at 05:07
  • thanks for the tip and much more – JayManHall Apr 06 '14 at 05:09