メニュー 閉じる

025. Processingでランダムな円を画面に充填してみる

シフマン先生の例を参考にやってみたかった平面充填です。

ArrayList<Circle> circles;

void setup () {

	size (800, 800);
	colorMode (HSB, 100);
	pixelDensity (2);

	circles = new ArrayList<Circle> ();

}

void draw () {

	background (0);

	int total = 10;
	int count = 0;
	int attempts = 0;

	while (count < total) {
		Circle nc = new_circle ();
		if (nc != null ) {
			circles.add (nc);
			count++;
		}
		attempts++;
		if (attempts > 1000) {
			noLoop ();
			println ("FINISHED");
			break;
		}

	}

	for (Circle c : circles) {
		if (c.growing) {
			if (c.edges ()) {
				c.growing = false;
			} else {
				for (Circle other : circles) {
					if (c != other) {
						float d = dist (c.x, c.y, other.x, other.y);
						if (d - 1 < c.r + other.r) {
							c.growing = false;
							break;
						}
					}
				}
			}
		}
		c.grow ();
		c.render ();
	}

}

Circle new_circle () {

	float x = random (width);
	float y = random (height);
	color c = color (random (100), 100, 100);

	boolean valid = true;

	for (Circle circle : circles) {
		float d = dist (x, y, circle.x, circle.y);
		if (d < circle.r) {
			valid = false;
			break;
		}
	}

	if (valid) {
		return new Circle (x, y, c);
	} else {
		return null;
	}

}
class Circle {

	float x;
	float y;
	float r;

	color c;

	boolean growing = true;

	Circle (float cx, float cy, color cc) {

		x = cx;
		y = cy;
		r = 1;

		c = cc;

	}

	void grow () {

		if (growing) {
			r += 0.5;
		}

	}

	boolean edges () {

		return (x + r > width || x - r < 0 || y + r > height || y - r < 0);

	}

	void render () {

		stroke (0, 0, 100);
		fill (c);
		ellipse (x, y, r * 2, r * 2);

	}

}

 

Posted in processing