Search code examples
javaloopsparametersgraphics2d

Java parameters in graphics


import java.awt.*;

public class CafeWall {
   public static final int mortar = 2;

   public static void main(String[] args) {
      DrawingPanel panel = new DrawingPanel(650, 400);
      panel.setBackground(Color.GRAY);
      Graphics g = panel.getGraphics();
      row(4, 20, 0, 0, g);
      row(4, 30, 50, 70, g);
      grid(0, 4, 25, 10, 150, g); 
      grid(10, 3, 25, 250, 200, g);
      grid(10, 5, 20, 425, 180, g);
      grid(35, 2, 35, 400, 20, g);


   }
   //This method will produce the two individual rows in CafeWall
   public static void row(int amount, int size, int x, int y, Graphics   g) {
      for(int squares = 0; squares < amount; squares++){
        g.setColor(Color.BLACK);
        g.fillRect(x+2*squares*size, y, size, size);
        g.setColor(Color.WHITE);
        g.fillRect(x+2*squares*size+size, y, size, size);
        g.setColor(Color.BLUE);
        g.drawLine(x+2*size*squares, y, x+2*squares*size+size, y+size);
        g.drawLine(x+2*size*squares, y+size, x+2*size*squares+size, y);
      }
   }
  //This method will produce the grids using the method row
   public static void grid(int indent, int amount, int size, int x, int   y, Graphics g) {
        for(int rows=0; rows<amount*2; rows++){
        row(amount, size, x+indent, y+rows*(size*mortar), g);

      }
  }
}

The CafeWall Illusion

In this program I am trying to code for the cafe wall illusion. I cannot use if statements. I have everything nearly done. The last part, in method grid, that codes for the x and y values is giving me a few problems. It looks like the y axis is correct. My x axis however is not working. What I think is happening is that all the rows are coming out on top of each other. But I am at a loss for how to code for my x variable. Every other row needs to be indented by a given amount. For example the middle bottom grid needs to be indented by 10 every other row. But I cannot do x + indent because that indents every row. Are there any hints?


Solution

  • I haven’t been able to test it since I don’t have your DrawingPanelclass. My idea is, in grid() draw two rows at a time, indenting only one of them:

        for (int rows = 0; rows < amount * 2; rows += 2) {
            row(amount, size, x, y + rows * (size * mortar), g);
            row(amount, size, x + indent, y + (rows + 1) * (size * mortar), g);
        }