Sierpinski triangle - java

The kth Sierpinski triangle is a triangle whose interior is sub-divided as follows:
Take the three mid-points of the sides of the triangle. These points form the
vertices of an inscribed triangle, which is colored black.
The remaining 3 inscribed triangles are (k-1)th Sierpinski triangles. complete the code of the drawTriangle
method in the SierpinskiTriangle class and a screenshot of the output of your Sierpinski program for k = 4.
I am really struggling here, I wrote this code but its not giving me what I need, any help and a step by step explanation will be very helpful. And my triangle don't stay, it disappears after a while. thanks in advance
import java.awt.*;
import javax.swing.*;
public class Sierpinski_Triangle extends JPanel {
private static int numberLevelsOfRecursion;
public Sierpinski_Triangle(int numLevels) {
numberLevelsOfRecursion = numLevels;
}
public void paintComponent(Graphics computerScreen) {
super.paintComponent(computerScreen);
Point top = new Point(250, 50);
Point left = new Point(50, 450);
Point right = new Point(450, 450);
drawTriangle(computerScreen, numberLevelsOfRecursion, top, left, right);
}
/**
* Draw a Sierpinski triangle
*
* #param screen
* the surface on which to draw the Sierpinski image
* #param levels
* number of levels of triangles-within-triangles
* #param top
* coordinates of the top point of the triangle
* #param left
* coordinates of the lower-left point of the triangle
* #param right
* coordinates of the lower-right point of the triangle
*/
public static void drawTriangle(Graphics g, int levels, Point top, Point left, Point right) {
/**
* You must COMPLETER THE CODE HERE to draw the Sierpinski Triangle
* recursive code needed to draw the Sierpinski Triangle
*/
Point p1 = top;
Point p2 = left;
Point p3 = right;
if (levels == 2) {
// base case: simple triangle
Polygon tri = new Polygon();
tri.addPoint(250, 50);
tri.addPoint(50, 450);
tri.addPoint(450, 450);
g.setColor(Color.RED);
g.fillPolygon(tri);
} else {
// Get the midpoint on each edge in the triangle
Point p12 = midpoint(p1, p2);
Point p23 = midpoint(p2, p3);
Point p31 = midpoint(p3, p1);
// recurse on 3 triangular areas
drawTriangle(g, levels - 1, p1, p12, p31);
drawTriangle(g, levels - 1, p12, p2, p23);
drawTriangle(g, levels - 1, p31, p23, p3);
}
}
private static Point midpoint(Point p1, Point p2) {
return new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
}
public static void main(String[] args) {
JFrame frame = new JFrame("SierpinskiTriangle");
Sierpinski_Triangle applet = new Sierpinski_Triangle(1);
frame.add(applet);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 450);
frame.setVisible(true);
}
}

Get rid of that fixed size triangle in the base case.
You have to change this:
tri.addPoint(250, 50);
tri.addPoint(50, 450);
tri.addPoint(450, 450);
to
tri.addPoint(p1.x, p1.y);
tri.addPoint(p2.x, p2.y);
tri.addPoint(p3.x, p3.y);
And as a guard against stack overflow, you should change this:
if (levels == 2) {
to this:
if (levels <= 2) {
And add more recursion level by setting the initial argument to higher than 1 (or you will only see that big red triangle):
Sierpinski_Triangle applet = new Sierpinski_Triangle(5);

You are setting the numberLevelsOfRecursion to 1 in the main method:
new Sierpinski_Triangle(1);
But you base case for the recursion is if (levels == 2), so your program basically hangs, because the level goes to "-infinity".
Also the code in the base case looks odd. It basically draws a big red triangle over everything drawn before. If your intention was to draw this at the beginning of the recursive process as some kind of borders for the picture, you shouldn't decrease the levels variable.

Related

Processing Tower Defence Game - Towers attacking Enemies

I will keep this short, I am making a Tower Defence game as a mini project while I have some spare time and I am trying to figure out how I can implement the towers to be able to shoot the enimies when they come into range using dist but I just don't know how to implement a method that uses the enimies position and the towers position. I have an ArrayList of CreepSprites and Towers
CreepSprite[] CreepSprites;
ArrayList<Tower> AllTowers = new ArrayList<Tower>();
ArrayList<Creep> AllCreeps = new ArrayList<Creep>();
If someone could give me some guidence as to how I would go about making the towers able to shoot the Creeps that would be great, even if it doesn't get rid of them, just able to shoot at them would be great.
Cheers
#GoneUp's answer is in the right direction. In Processing you have a class called PVector which provides a distance method as well: dist()
PVector towerPos = new PVector(100, 100);
PVector enemyPos = new PVector(300, 300);
float towerAttackRadius = 200;
void setup() {
size(400, 400);
rectMode(CENTER);
strokeWeight(3);
}
void draw() {
background(255);
//draw tower
noFill();
//check range
if(towerPos.dist(enemyPos) < towerAttackRadius){
//tower engaged, draw in green
stroke(0,192,0);
}else{
//tower in idle mode, draw in blue
stroke(0, 0, 192);
}
//visualise tower attack radius
//(towerAttackRadius * 2 -> radius * 2 = diameter (width/height))
ellipse(towerPos.x, towerPos.y, towerAttackRadius * 2, towerAttackRadius * 2);
//visualise tower
rect(towerPos.x, towerPos.y, 30, 30);
//draw enemy
stroke(192, 0, 0);
rect(enemyPos.x, enemyPos.y, 10, 10);
//instructions
fill(0);
text("click and drag to move enemy",10,15);
}
void mouseDragged() {
enemyPos.set(mouseX, mouseY);
}
I warmly recommend Daniel Shiffman's Nature of Code chapter on Vectors.
It's a little bit of linear algebra, but it's super useful, especially for games so worth getting the hang of it early.
For example, to shoot a bullet, you will need to workout the direction towards.
You can do that by using vector subtraction.
Additionally, you probably want to control how fast the bullet moves on screen towards that direction. That can also be done by normalising the vector: keeping it's direction, but reducing it's size to 1.0:
After that point it's easy to scale (multiply) the vector to any size you want.
If you know the tower's position, you simply need to add this scaled velocity to compute where the bullet should be drawn each frame.
PVector already has a function that does both: setMag().
(set mag is short for set magnitude (or vector length))
It also provides a heading() function which is handy to workout the angle.
Here's a basic proof of concept:
PVector towerPos = new PVector(100, 100);
PVector enemyPos = new PVector(300, 300);
float towerAttackRadius = 300;
ArrayList<Bullet> bullets = new ArrayList<Bullet>();
void setup() {
size(400, 400);
rectMode(CENTER);
strokeWeight(3);
}
void draw() {
background(255);
//check if an enemy is within range using dist()
//if the distance is smaller than the radius, attack!
if(towerPos.dist(enemyPos) < towerAttackRadius){
//hacky frame based counter: please use a millis() based timer instead
//shoot every 30 frames
if(frameCount % 30 == 0){
shoot();
}
}
//update bullets
for(Bullet b : bullets) {
b.update();
}
//draw tower
noFill();
stroke(0, 0, 192);
//visualise tower attack radius
//(towerAttackRadius * 2 -> radius * 2 = diameter (width/height))
ellipse(towerPos.x, towerPos.y, towerAttackRadius * 2, towerAttackRadius * 2);
//visualise tower
rect(towerPos.x, towerPos.y, 30, 30);
//draw enemy
stroke(192, 0, 0);
rect(enemyPos.x, enemyPos.y, 10, 10);
//instructions
fill(0);
text("click and drag to move enemy",10,15);
}
void mouseDragged() {
enemyPos.set(mouseX, mouseY);
}
void shoot(){
//make a new Bullet pointing from the tower to the enemy
Bullet b = new Bullet(towerPos.x,towerPos.y,enemyPos.x,enemyPos.y);
//add it to the list of bullets (for updates)
bullets.add(b);
println(b);
}
class Bullet {
//where does the bullet shoot from (and it's current position)
PVector position = new PVector();
//where does the bullet shooting towards
PVector target = new PVector();
//how fast does the bullet move on screen
float speed = 1.2;
//how large goes the bullet appear on screen
float size = 10;
//bullet velocity
PVector velocity;
Bullet(float startX,float startY, float endX, float endY) {
position.set(startX,startY);
target.set(endX,endY);
//compute the difference vector (start to end) = direction
velocity = PVector.sub(target,position);
//normalize the vector = same direction but magnitude of 1 -> makes it easy to scale
//velocity.normalize();
//scale by the speed to move on screen)
//normalize + multiple = resize the vector -> same direction, different length
//velocity.mult(speed);
//or do both normalize and multiple using setMag()
velocity.setMag(speed);
}
void update() {
//update position based on velocity (simply add velocity to current position)
position.add(velocity);
//render
//compute rotation angle from velocity (implementation is 2D only btw)
float angle = velocity.heading();
pushMatrix();
translate(position.x,position.y);
rotate(angle);
stroke(0);
line(0,0,size,0);
popMatrix();
}
String toString(){
return position+"->"+target;
}
}
You can actually play with a preview bellow:
var towerPos,enemyPos;
var towerAttackRadius = 300;
var bullets = [];
function setup() {
createCanvas(400, 400);
rectMode(CENTER);
strokeWeight(3);
towerPos = createVector(100, 100);
enemyPos = createVector(300, 300);
}
function draw() {
background(255);
//check if an enemy is within range using dist()
//if the distance is smaller than the radius, attack!
if(towerPos.dist(enemyPos) < towerAttackRadius){
//hacky frame based counter: please use a millis() based timer instead
//shoot every 30 frames
if(frameCount % 30 === 0){
shoot();
}
}
//update bullets
for(var i = 0; i < bullets.length; i++) {
bullets[i].update();
}
//draw tower
noFill();
stroke(0, 0, 192);
//visualise tower attack radius
//(towerAttackRadius * 2 -> radius * 2 = diameter (width/height))
ellipse(towerPos.x, towerPos.y, towerAttackRadius * 2, towerAttackRadius * 2);
//visualise tower
rect(towerPos.x, towerPos.y, 30, 30);
//draw enemy
stroke(192, 0, 0);
rect(enemyPos.x, enemyPos.y, 10, 10);
//instructions
noStroke();
fill(0);
text("click and drag to move enemy",10,15);
}
function mouseDragged() {
enemyPos.set(mouseX, mouseY);
}
function shoot(){
//make a new Bullet pointing from the tower to the enemy
var b = new Bullet(towerPos.x,towerPos.y,enemyPos.x,enemyPos.y);
//add it to the list of bullets (for updates)
bullets.push(b);
}
function Bullet(startX,startY,endX,endY) {
//where does the bullet shoot from (and it's current position)
this.position = createVector(startX,startY);
//where does the bullet shooting towards
this.target = createVector(endX,endY);
//how fast does the bullet move on screen
this.speed = 1.2;
//how large goes the bullet appear on screen
this.size = 10;
//compute the difference vector (start to end) = direction
this.velocity = p5.Vector.sub(this.target,this.position);
//normalize the vector = same direction but magnitude of 1 -> makes it easy to scale
this.velocity.normalize();
//scale by the speed to move on screen)
//normalize + multiple = resize the vector -> same direction, different length
this.velocity.mult(this.speed);
this.update = function() {
//update position based on velocity (simply add velocity to current position)
this.position.add(this.velocity);
//render
//compute rotation angle from velocity (implementation is 2D only btw)
var angle = this.velocity.heading();
push();
translate(this.position.x,this.position.y);
rotate(angle);
stroke(0);
line(0,0,this.size,0);
pop();
}
}
//http://stackoverflow.com/questions/39698472/processing-tower-defence-game-towers-attacking-enemies
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.3/p5.min.js"></script>
Have fun with PVectors ! :)
One important note:
the above code is a proof of concept and not optimized.
On the long run with a lot of towers and enemies it will slow down.
Once you get the math/code right, you can start doing a few improvements:
manage bullets/instances (e.g. re-use bullets that are off screen
rather than creating new instances all the time)
use the squared distance via magSq() instead and the squared radius to speed up calculations
You could use the Point2D class to represent the x,y coordinates of your figures. The class got a pre-implemented distance method wich can be checked against a radius.

Snap to Edge Effect

My final goal is to have a method, lets say:
Rectangle snapRects(Rectangle rec1, Rectangle rec2);
Imagine a Rectangle having info on position, size and angle.
Dragging and dropping the ABDE rectangle close to the BCGF rectangle would call the method with ABDE as first argument and BCGF as second argument, and the resulting rectangle is a rectangle lined up with BCGF's edge.
The vertices do not have to match (and preferrably won't so the snapping isn't so restrictive).
I can only understand easily how to give the same angle, but the position change is quite confusing to me. Also, i believe even if i reached a solution it would be quite badly optimized (excessive resource cost), so I would appreciate guidance on this.
(This has already been asked but no satisfatory answer was given and the question forgotten.)
------------------------------------------------------------------
Edit: It seems my explanation was insufficient so I will try to clarify my wishes:
The following image shows the goal of the method in a nutshell:
Forget about "closest rectangle", imagine there are just two rectangles. The lines inside the rectangles represent the direction they are facing (visual aid for the angle).
There is a static rectangle, which is not to be moved and has an angle (0->360), and a rectangle (also with an angle) which I want to Snap to the closest edge of the static rectangle. By this, i mean, i want the least transformations possible for the "snap to edge" to happen.
This brings many possible cases, depending on the rotation of the rectangles and their position relative to each other.
The next image shows the static rectangle and how the position of the "To Snap" rectangle changes the snapping result:
The final rotations might not be perfect since it was done by eye, but you get the point, it matters the relative position and also both angles.
Now, in my point of view, which may be completely naive, I see this problem solved on two important and distinct steps on transforming the "To Snap" rectangle: Positioning and Rotation
Position: The objective of the new position is to stick to the closest edge, but since we want it to stick paralell to the static rectangle, the angle of the static rectangle matters. The next image shows examples of positioning:
In this case, the static rectangle has no angle, so its easy to determine up, down, left and right. But with angle, there are alot more possibilities:
As for the rotation, the goal is for the "to snap" rectangle to rotate the minimum needed to become paralell with the static rectangle:
As a final note, in regard of implementation input, the goal is to actually drag the "to snap" rectangle to wherever position i wish around the static rectangle and by pressing a keyboard key, the snap happens.
Also, it appears i have exagerated a little when i asked for optimization, to be honest i do not need or require optimization, I do prefer an easy to read, step by step clear code (if its the case), rather than any optimization at all.
I hope i was clear this time, sorry for the lack of clarity in the first place, if you have any more doubts please do ask.
The problem is obviously underspecified: What does "line up" for the edges mean? A common start point (but not necessarily a common end point)? A common center point for both edges? (That's what I assumed now). Should ALL edges match? What is the criterion for deciding WHICH edge of the first rectangle should be "matched" with WHICH edge of the second rectangle? That is, imagine one square consists exactly of the center points of the edges of the other square - how should it be aligned then?
(Secondary question: In how far is optimization (or "low resource cost") important?)
However, I wrote a few first lines, maybe this can be used to point out more clearly what the intended behavior should be - namely by saying in how far the intended behavior differs from the actual behavior:
EDIT: Old code omitted, update based on the clarification:
The conditions for the "snapping" are still not unambiguous. For example, it is not clear whether the change in position or the change in the angle should be preferred. But admittedly, I did not figure out in detail all possible cases where this question could arise. In any case, based on the updated question, this might be closer to what you are looking for.
NOTE: This code is neither "clean" nor particularly elegant or efficient. The goal until now was to find a method that delivers "satisfactory" results. Optimizations and beautifications are possible.
The basic idea:
Given are the static rectangle r1, and the rectangle to be snapped, r0
Compute the edges that should be snapped together. This is divided in two steps:
The method computeCandidateEdgeIndices1 computes the "candidate edges" (resp. their indices) of the static rectangle that the moving rectangle may be snapped to. This is based on the folowing criterion: It checks how many vertices (corners) of the moving rectangle are right of the particular edge. For example, if all 4 vertices of the moving rectangle are right of edge 2, then edge 2 will be a candidate for snapping the rectangle to.
Since there may be multiple edges for which the same number of vertices may be "right", the method computeBestEdgeIndices computes the candidate edge whose center has the least distance to the center of any edge of the moving rectangle. The indices of the respective edges are returned
Given the indices of the edges to be snapped, the angle between these edges is computed. The resulting rectangle will be the original rectangle, rotated by this angle.
The rotated rectangle will be moved so that the centers of the snapped edges are at the same point
I tested this with several configurations, and the results at least seem "feasible" for me. Of course, this does not mean that it works satisfactory in all cases, but maybe it can serve as a starting point.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class RectangleSnap
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RectangleSnapPanel panel = new RectangleSnapPanel();
f.getContentPane().add(panel);
f.setSize(1000,1000);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class SnapRectangle
{
private Point2D position;
private double sizeX;
private double sizeY;
private double angleRad;
private AffineTransform at;
SnapRectangle(
double x, double y,
double sizeX, double sizeY, double angleRad)
{
this.position = new Point2D.Double(x,y);
this.sizeX = sizeX;
this.sizeY = sizeY;
this.angleRad = angleRad;
at = AffineTransform.getRotateInstance(
angleRad, position.getX(), position.getY());
}
double getAngleRad()
{
return angleRad;
}
double getSizeX()
{
return sizeX;
}
double getSizeY()
{
return sizeY;
}
Point2D getPosition()
{
return position;
}
void draw(Graphics2D g)
{
Color oldColor = g.getColor();
Rectangle2D r = new Rectangle2D.Double(
position.getX(), position.getY(), sizeX, sizeY);
AffineTransform at = AffineTransform.getRotateInstance(
angleRad, position.getX(), position.getY());
g.draw(at.createTransformedShape(r));
g.setColor(Color.RED);
for (int i=0; i<4; i++)
{
Point2D c = getCorner(i);
Ellipse2D e = new Ellipse2D.Double(c.getX()-3, c.getY()-3, 6, 6);
g.fill(e);
g.drawString(""+i, (int)c.getX(), (int)c.getY()+15);
}
g.setColor(Color.GREEN);
for (int i=0; i<4; i++)
{
Point2D c = getEdgeCenter(i);
Ellipse2D e = new Ellipse2D.Double(c.getX()-3, c.getY()-3, 6, 6);
g.fill(e);
g.drawString(""+i, (int)c.getX(), (int)c.getY()+15);
}
g.setColor(oldColor);
}
Point2D getCorner(int i)
{
switch (i)
{
case 0:
return new Point2D.Double(position.getX(), position.getY());
case 1:
{
Point2D.Double result = new Point2D.Double(
position.getX(), position.getY()+sizeY);
return at.transform(result, null);
}
case 2:
{
Point2D.Double result = new Point2D.Double
(position.getX()+sizeX, position.getY()+sizeY);
return at.transform(result, null);
}
case 3:
{
Point2D.Double result = new Point2D.Double(
position.getX()+sizeX, position.getY());
return at.transform(result, null);
}
}
return null;
}
Line2D getEdge(int i)
{
Point2D p0 = getCorner(i);
Point2D p1 = getCorner((i+1)%4);
return new Line2D.Double(p0, p1);
}
Point2D getEdgeCenter(int i)
{
Point2D p0 = getCorner(i);
Point2D p1 = getCorner((i+1)%4);
Point2D c = new Point2D.Double(
p0.getX() + 0.5 * (p1.getX() - p0.getX()),
p0.getY() + 0.5 * (p1.getY() - p0.getY()));
return c;
}
void setPosition(double x, double y)
{
this.position.setLocation(x, y);
at = AffineTransform.getRotateInstance(
angleRad, position.getX(), position.getY());
}
}
class RectangleSnapPanel extends JPanel implements MouseMotionListener
{
private final SnapRectangle rectangle0;
private final SnapRectangle rectangle1;
private SnapRectangle snappedRectangle0;
RectangleSnapPanel()
{
this.rectangle0 = new SnapRectangle(
200, 300, 250, 200, Math.toRadians(-21));
this.rectangle1 = new SnapRectangle(
500, 300, 200, 150, Math.toRadians(36));
addMouseMotionListener(this);
}
#Override
protected void paintComponent(Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D)gr;
g.setColor(Color.BLACK);
rectangle0.draw(g);
rectangle1.draw(g);
if (snappedRectangle0 != null)
{
g.setColor(Color.BLUE);
snappedRectangle0.draw(g);
}
}
#Override
public void mouseDragged(MouseEvent e)
{
rectangle0.setPosition(e.getX(), e.getY());
snappedRectangle0 = snapRects(rectangle0, rectangle1);
repaint();
}
#Override
public void mouseMoved(MouseEvent e)
{
}
private static SnapRectangle snapRects(
SnapRectangle r0, SnapRectangle r1)
{
List<Integer> candidateEdgeIndices1 =
computeCandidateEdgeIndices1(r0, r1);
int bestEdgeIndices[] = computeBestEdgeIndices(
r0, r1, candidateEdgeIndices1);
int bestEdgeIndex0 = bestEdgeIndices[0];
int bestEdgeIndex1 = bestEdgeIndices[1];
System.out.println("Best to snap "+bestEdgeIndex0+" to "+bestEdgeIndex1);
Line2D bestEdge0 = r0.getEdge(bestEdgeIndex0);
Line2D bestEdge1 = r1.getEdge(bestEdgeIndex1);
double edgeAngle = angleRad(bestEdge0, bestEdge1);
double rotationAngle = edgeAngle;
if (rotationAngle <= Math.PI)
{
rotationAngle = Math.PI + rotationAngle;
}
else if (rotationAngle <= -Math.PI / 2)
{
rotationAngle = Math.PI + rotationAngle;
}
else if (rotationAngle >= Math.PI)
{
rotationAngle = -Math.PI + rotationAngle;
}
SnapRectangle result = new SnapRectangle(
r0.getPosition().getX(), r0.getPosition().getY(),
r0.getSizeX(), r0.getSizeY(), r0.getAngleRad()-rotationAngle);
Point2D edgeCenter0 = result.getEdgeCenter(bestEdgeIndex0);
Point2D edgeCenter1 = r1.getEdgeCenter(bestEdgeIndex1);
double dx = edgeCenter1.getX() - edgeCenter0.getX();
double dy = edgeCenter1.getY() - edgeCenter0.getY();
result.setPosition(
r0.getPosition().getX()+dx,
r0.getPosition().getY()+dy);
return result;
}
// Compute for the edge indices for r1 in the given list
// the one that has the smallest distance to any edge
// of r0, and return this pair of indices
private static int[] computeBestEdgeIndices(
SnapRectangle r0, SnapRectangle r1,
List<Integer> candidateEdgeIndices1)
{
int bestEdgeIndex0 = -1;
int bestEdgeIndex1 = -1;
double minCenterDistance = Double.MAX_VALUE;
for (int i=0; i<candidateEdgeIndices1.size(); i++)
{
int edgeIndex1 = candidateEdgeIndices1.get(i);
for (int edgeIndex0=0; edgeIndex0<4; edgeIndex0++)
{
Point2D p0 = r0.getEdgeCenter(edgeIndex0);
Point2D p1 = r1.getEdgeCenter(edgeIndex1);
double distance = p0.distance(p1);
if (distance < minCenterDistance)
{
minCenterDistance = distance;
bestEdgeIndex0 = edgeIndex0;
bestEdgeIndex1 = edgeIndex1;
}
}
}
return new int[]{ bestEdgeIndex0, bestEdgeIndex1 };
}
// Compute the angle, in radians, between the given lines,
// in the range (-2*PI, 2*PI)
private static double angleRad(Line2D line0, Line2D line1)
{
double dx0 = line0.getX2() - line0.getX1();
double dy0 = line0.getY2() - line0.getY1();
double dx1 = line1.getX2() - line1.getX1();
double dy1 = line1.getY2() - line1.getY1();
double a0 = Math.atan2(dy0, dx0);
double a1 = Math.atan2(dy1, dx1);
return (a0 - a1) % (2 * Math.PI);
}
// In these methods, "right" refers to screen coordinates, which
// unfortunately are upside down in Swing. Mathematically,
// these relation is "left"
// Compute the "candidate" edges of r1 to which r0 may
// be snapped. These are the edges to which the maximum
// number of corners of r0 are right of
private static List<Integer> computeCandidateEdgeIndices1(
SnapRectangle r0, SnapRectangle r1)
{
List<Integer> bestEdgeIndices = new ArrayList<Integer>();
int maxRight = 0;
for (int i=0; i<4; i++)
{
Line2D e1 = r1.getEdge(i);
int right = countRightOf(e1, r0);
if (right > maxRight)
{
maxRight = right;
bestEdgeIndices.clear();
bestEdgeIndices.add(i);
}
else if (right == maxRight)
{
bestEdgeIndices.add(i);
}
}
//System.out.println("Candidate edges "+bestEdgeIndices);
return bestEdgeIndices;
}
// Count the number of corners of the given rectangle
// that are right of the given line
private static int countRightOf(Line2D line, SnapRectangle r)
{
int count = 0;
for (int i=0; i<4; i++)
{
if (isRightOf(line, r.getCorner(i)))
{
count++;
}
}
return count;
}
// Returns whether the given point is right of the given line
// (referring to the actual line *direction* - not in terms
// of coordinates in 2D!)
private static boolean isRightOf(Line2D line, Point2D point)
{
double d00 = line.getX1() - point.getX();
double d01 = line.getY1() - point.getY();
double d10 = line.getX2() - point.getX();
double d11 = line.getY2() - point.getY();
return d00 * d11 - d10 * d01 > 0;
}
}

Drawing a Fractal Pattern composed of Circles Using Java

I've been working on this project for last week and can't figure out how to fix it. I feel like I'm so close but can't spot my error!
My assignment calls for me to draw circles along an imaginary line using the Java Graphics class. Draw a circle in the center with a radius of n. Then draw two circles with radius of n/2 whose endpoints intersect with the left and right arc of the circle.
I have been able to draw the 2nd step of two circles to the right and left of the first circle. However, my program is supposed to then draw four circles of the same size recursively. One circle to both the right and left side of the left circle AND one circle to both the right and left side of the right circle. Something is suspect with my code.
Any help would be greatly appreciated.
package fractalcircles;
import java.awt.*;
import javax.swing.*;
public class FractalCircles {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{ //create a MyCanvas object
MyCanvas canvas1 = new MyCanvas();
//set up a JFrame to hold the canvas
JFrame frame = new JFrame();
frame.setTitle("FractalCircles.java");
frame.setSize(500,500);
frame.setLocation(100,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the canvas to the frame as a content panel
frame.getContentPane().add(canvas1);
frame.setVisible(true);
}//end main
}//end class
class MyCanvas extends Canvas
{
public MyCanvas()
{} //end MyCanvas() constructor
//this method will draw the initial circle and invisible line
public void paint (Graphics graphics)
{
int x1,x2,y1,y2; //future x and y coordinates
int radius=125; //radius of first circle
int xMid=250, yMid=250; //center point (x,y) of circle
//draw invisible line
graphics.drawLine(0,250,500,250);
//draw first circle
graphics.drawOval(xMid-radius,yMid-radius,radius*2,radius*2);
//run fractal algorithm to draw 2 circles to the left and right
drawCircles(graphics, xMid, yMid, radius);
}
void drawCircles (Graphics graphics, int xMid, int yMid, int radius)
{
//used to position left and right circles
int x1 = xMid-radius-(radius/2);
int y1 = yMid-(radius/2);
int x2 = xMid+radius-(radius/2);
int y2= yMid-(radius/2);
if (radius > 5)
{
//draw circle to the left
graphics.drawOval(x1, y1, (radius/2)*2, (radius/2)*2);
//draw circle to the right
graphics.drawOval(x2, y2, (radius/2)*2, (radius/2)*2);
}
drawCircles (graphics, xMid, yMid, radius/2);
}
Some adapted version using recursion...
Draw the circle, then draw its 2 children by calling the same function again.
void drawCircles(Graphics graphics, int xMid, int yMid, int radius) {
// end recursion
if(radius < 5)
return;
// Draw circle
graphics.drawOval(xMid - radius, yMid - radius, radius * 2, radius * 2);
// start recursion
//left
drawCircles(graphics, xMid-radius, yMid, radius / 2);
//right
drawCircles(graphics, xMid+radius, yMid, radius / 2);
}
It looks to be like you only have one drawCircles call inside your drawCircles function. This can't be right because each time you draw a circle you need to call the recursive function twice. I see that you are drawing two circles, but that is actually backwards.
To get this to work, you need to draw one circle, and call the recursive function twice.
Here is what you need to change:
Make it so that the drawCircle draws one circle, centered on the coordinates
in drawCircle, call drawCircle twice, once with the left circle coords, once with the right
That should do it.
You are only drawing 1 circle from each side of the big circle. You need to change the code. I only write a short fix but don't tested. Good luck
void drawCircles (Graphics graphics, int xMid, int yMid, int radius)
{
//used to position left and right circles
int x1 = xMid-radius-(radius/2);
int x2 = xMid+radius-(radius/2);
int x3 = xMid+radius+(radius/2);
int x4 = xMid-radius+(radius/2);
int y = yMid-(radius/2);
if (radius > 5)
{
//draw 4 circles
graphics.drawOval(x1, y, (radius/2)*2, (radius/2)*2);
graphics.drawOval(x2, y, (radius/2)*2, (radius/2)*2);
graphics.drawOval(x3, y, (radius/2)*2, (radius/2)*2);
graphics.drawOval(x4, y, (radius/2)*2, (radius/2)*2);
}
//left
drawCircles(graphics, xMid-radius, yMid, radius / 2);
//right
drawCircles(graphics, xMid+radius, yMid, radius / 2);
}

Java Methods to rotate, increase size, and clear Box image in Java

I'm creating a java program to draw an image of a box. I have most of my code finished. But, I'm having trouble figuring out a method to rotate the box by a specific number of degrees. I'm also trying to create a method to increase the size of the box by percentage and to clear my canvas of all images drawn.
This is the code I have thus far:
// My Box class
import java.awt.Rectangle;
public class Box
{
public Box(Shapes canvasRef, int leftSide, int topLeft, int theWidth, int theHeight)
{
left = leftSide;
top= topLeft;
width = theWidth;
height = theHeight;
canvas = canvasRef;
theBox = new Rectangle(left, top, width, height);
canvas.addToDisplayList(this);
show = false;
}
public void draw()
{
show = true;
theBox = new Rectangle(left, top, width, height);
canvas.boxDraw();
}
public void unDraw()
{
show = false;
theBox = new Rectangle(left, top, width, height);
canvas.boxDraw();
}
public Rectangle getBox()
{
return theBox;
}
public void moveTo(int newX, int newY)
{
left = newX;
top = newY;
draw();
}
// This is the method that I tried but doesn't do anything
public void turn(int degrees)
{
int newAngle = angle + degrees;
angle = newAngle % 60;
}
clearWorld()
{
// Clears the "canvas" upon which boxes are drawn
}
public void grow(int percentage)
{
//The box grows the specified percentage,
about the center, i.e. increase each side of the box
the percentage indicated, with the center unchanged
}
// My Driver Program
import javax.swing.JFrame;
public class DisplayList
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Joe The Box");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
Shapes component = new Shapes();
frame.add(component);
frame.setVisible(true);
Box b1 = new Box(component, 150, 100, 30, 50);
Box b2 = new Box(component, 100, 100, 40, 60);
b1.draw();
b2.draw();
b1.turn(90);
b2.grow(100);
b1.clearWorld();
Delay.sleep(2);
b2.moveTo(10,10);
}
}
public boolean showBox()
{
return show;
}
private int left;
private int top;
private int width;
private int height;
private int angle = 0;
private Shapes canvas;
private Rectangle theBox;
private boolean show;
}
Can anyone please help me with the last three methods of my Box class?
I'm really struck on what to add?
I'm open to any suggestions.
Thanks for your time!
If you are rotating the box around (0,0) pre-multiply each coordinate, by a rotation matrix:
x=x*Math.cos(t)-y*Math.sin(t)//result of matrix multiplication.
y=x*Math.sin(t)+y*Math.cos(t)//t is the angle
Alternatively, convert to polar coordinates, r=Math.hypot(x,y) theta=Math.atan2(x,y) and add an angle to theta: theta+= rotationAngle. Then convert back to rectangular coordinates: x=r*Math.cos(theta) y=r*Math.sin(theta)
By the way you don't need the modulus; Angles greater than 360 are also ok. Oh, and all angles should be in radians. If they are in degrees, first multiply by 2pi/360 to convert them to radians.
To scale the box, multiply each coordinate by a constant scaling factor.
There are at least two ways to rotate a point around the origin, both of which are mathematically equivalent:
Use trigonometry to calculate the new (x, y) coordinates for the point.
Use linear algebra, specifically a linear transformation matrix, to represent the rotation.
I suggest that you google some keywords to learn more about either of these solutions. If you encounter specific details that you don't understand, please come back with more questions. You may also want to check out our sister site http://math.stackexchange.com where you can ask questions which are specific to the mathematics behind rotation animations.
Once you understand how to apply a rotation to a single point, you will simply need to repeat the calculations for each of the vertices of your box. This will be easiest if you encapsulate the calculations for a single point into its own method.

how to save values of variables and prevent them from changing when doing recursion? also recursion assistance?

import gpdraw.*;
public class Y2K {
// Attributes
SketchPad pad;
DrawingTool pen;
// Constructor
public Y2K() {
pad = new SketchPad(600, 600, 50);
pen = new DrawingTool(pad);
// Back the pen up so the Y is drawn in the middle of the screen
pen.up();
pen.setDirection(270);
pen.forward(150);
pen.down();
pen.setDirection(90);
}
public void drawY(int level, double length) {
// Base case: Draw an Y
if (level == 0) {
//pen.setDirection(90);
pen.forward(length);
pen.turnRight(60);
pen.forward(length);
pen.backward(length);
pen.turnLeft(120);
pen.forward(length);
pen.backward(length);
}
// Recursive case: Draw an L at each midpoint
// of the current L's segments
else {
//Drawing the bottom "leg" of our Y shape
pen.forward(length / 2);
double xpos1 = pen.getXPos();
double ypos1 = pen.getYPos();
double direction1 = pen.getDirection();
pen.turnRight(90);
drawY(level - 1, length / 2.0);
pen.up();
pen.move(xpos1, ypos1);
pen.setDirection(direction1);
pen.down();
pen.forward(length / 2);
double xpos2 = pen.getXPos();
double ypos2 = pen.getYPos();
double direction2 = pen.getDirection();
//Drawing upper Right Leg
pen.turnRight(60);
pen.forward(length / 2); //going to the midpoint
double xpos3 = pen.getXPos();
double ypos3 = pen.getYPos();
double direction3 = pen.getDirection();
pen.turnLeft(90);
drawY(level - 1, length / 2.0);
pen.up();
pen.move(xpos3, ypos3);
pen.setDirection(direction3);
pen.down();
pen.forward(length / 2);
//drawing upper left leg
pen.up();
pen.move(xpos1, ypos1);
pen.setDirection(direction1);
pen.down();
pen.forward(length / 2);
pen.turnLeft(60);
pen.forward(length / 2);
double xpos4 = pen.getXPos();
double ypos4 = pen.getYPos();
double direction4 = pen.getDirection();
pen.turnLeft(90);
drawY(level - 1, length / 2.0);
pen.up();
pen.move(xpos4, ypos4);
pen.setDirection(direction4);
pen.down();
pen.forward(length / 2);
pen.forward(length / 2);
}
}
public static void main(String[] args) {
Y2K fractal = new Y2K();
// Draw Y with given level and side length
fractal.drawY(8, 200);
}
}
output:
one certain leg of the triangle is too long, and that makes the output slightly off. maybe its because the code went (length/2) too far? lets debug this.
otherwise it is completely fine, the recursion is great, and its exactly what i wanted to do
As you're constantly drawing Y's, I'd recommend you create a method that draws a Y given certain parameters (e.g. length, angle of separation between the two branches of the Y, rotation, etc.). This will make your code much more readable and easier to understand.
As for moving to the center, just think of the Y on a coordinate plane. Based upon the rotation of the Y, and its starting point you can calculate the center point.
Just break it up into its x and y components.
Given this information, we can solve for a and for b.
a = length * sin(θ)
b = length * cos(θ)
Then add this to your x and y to calculate the center point of the Y.
As for keeping the constant length, you know the level. At the first level, level == 1. But the length of this next level should be length * (2^level). In this case, length/2 (as length would be -1).
In pseudo code terms:
public void drawY(int level, double length)
{
//Drawing the bottom "leg" of our Y shape
Move Forward length/2
Save our position
Save our direction
Turn to the right 90 degrees
Recursion (call drawY())
revert to original location
revert to original direction
move forward length/2 (to go to center point of Y)
save our new position
save our new direction
//Drawing upper Right Leg
Turn 60 to the right
Move Forward length/2 //going to the midpoint
save our new position (don't forget the center point)
save our new direction (don't forget the center point direction)
Turn 90 to the left
Recursion (call drawY())
return to our saved position (not center one)
return to our saved direction (not center one)
move forward length/2
//drawing upper left leg
return to center point
return to center direction
turn left 60
move forward length/2
save position (you can overwrite the center one now
save direction (you can overwrite)
turn left 90
Recursion (call drawY())
return to position
return to direction
move forward length/2
}

Categories