Back Next

Clockwise or anticlockwise?

Click 3 points and the program'll tell you if you clicked in a clockwise or anticlockwise direction:

Credits: This is an Applet adaptation of a program by Pete Williams.

Code:

// clockwise.java
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class clockwise extends Applet

int n=0;
int[][] coords=new int[3][2];
static Point A,B,C;

public void init()

setSize(500, 500);
show(); 
this.addMouseListener
(new MouseAdapter()

public void mousePressed(MouseEvent evt)
{
int x,y;
x = evt.getX(); 
y = evt.getY();
if(n==3)n=0;
else 
{
coords[n][0]=x;
coords[n][1]=y;
n++;
}
repaint();
}
}
);
}


static float area(Point A, Point B, Point C)

return ((A.x - C.x) * (B.y - C.y) - (A.y - C.y) * (B.x - C.x))/2;
}

public void paint(Graphics g)

int x,y;
g.setColor(Color.blue);
for(int i=0;i<n;i++)
{
x=coords[i][0];
y=coords[i][1];
g.drawString("Point (" + x +","+y+")", 10, 15+i*15);
g.drawLine(x,y,x,y);//draws a blue pixel at (x,y) 
}
if(n==3)
{
A=new Point(coords[0][0],coords[0][1]);
B=new Point(coords[1][0],coords[1][1]);
C=new Point(coords[2][0],coords[2][1]);
if(area(A,B,C)==0.0) g.drawString("3 points on a straight line", 10, 60);
else if(area(A,B,C)>0) g.drawString("3 points clockwise", 10, 60);
else if(area(A,B,C)<0) g.drawString("3 points anti-clockwise", 10, 60);
}
}
}

Up