Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 10-24-2012, 11:28 PM   PM User | #1
itsalltech
New Coder

 
Join Date: Mar 2010
Posts: 22
Thanks: 1
Thanked 0 Times in 0 Posts
itsalltech is an unknown quantity at this point
Sierpinski Carpet and overlapping squares

Hello,

I'm trying to finish a program that produces a Sierpinski Carpet fractal, but the squares that the program prints are appearing over each other. The program should print the overlapping squares underneath each other, however. I'm not sure how to fix the problem, but I know it has something to do with the placement of the final fillRect line.

Thoughts? Thank you.


Code:
import java.awt.Color;
import java.awt.Graphics;
import java.util.*;
public class Sierpinski {
 public static final int PANEL_SIZE = 243;
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  DrawingPanel panel = new DrawingPanel(PANEL_SIZE, PANEL_SIZE);
  Graphics g = panel.getGraphics();
  int width = PANEL_SIZE / 3;
  int height = PANEL_SIZE / 3;
  int x = PANEL_SIZE / 3;
  int y = PANEL_SIZE / 3;
  System.out.print("Please enter an integer: ");
  int limit = input.nextInt();
  draw(limit, g, x, y, width, height);
 }

 public static void draw(int limit, Graphics g, int x, int y, int width,int height) {
  Random randNum = new Random();
  int numberRed = randNum.nextInt(255) + 1;
  int numberBlue = randNum.nextInt(255) + 1;
  int numberGreen = randNum.nextInt(255) + 1;
  Color randColor = new Color(numberRed, numberGreen, numberBlue);
  g.setColor(randColor);
  if (limit <= 0) {
   return;
  }
  if (limit == 1) {
   g.fillRect(x, y, width, height);
  }
  else {
   g.fillRect(x, y, width, height);
   width /= 3;
   height /= 3;
   // separating into 3x3 grid
   int x1 = x - 2 * width;
   int y1 = y - 2 * height;
   int x2 = x + width;
   int y2 = y + height;
   int x3 = x + 4 * width;
   int y3 = y + 4 * height;
   draw(limit - 1, g, x1, y1, width, height);
   draw(limit - 1, g, x2, y1, width, height);
   draw(limit - 1, g, x3, y1, width, height);
   draw(limit - 1, g, x1, y2, width, height);
   draw(limit - 1, g, x1, y3, width, height);
   draw(limit - 1, g, x2, y3, width, height);
   draw(limit - 1, g, x2, y2, width, height);
   draw(limit - 1, g, x3, y3, width, height);
   draw(limit - 1, g, x3, y2, width, height);
  }
 }
}
itsalltech is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:46 PM.


Advertisement
Log in to turn off these ads.