定义形状
基础形状的定义:点,线段,射线,矩形,旋转矩形,三角形,圆,多边形
其中矩形,旋转矩形,三角形均可算作是多边形
具体形状类的实现:
//点的定义
public class Point
{
public float X { get; set; }
public float Y { get; set; }
public Point(float x, float y)
{
X = x;
Y = y;
}
}
//线段的定义
public class LineSegment
{
public Point StartPoint { get; set; } // 线段起点
public Point EndPoint { get; set; } // 线段终点
public LineSegment(Point startPoint, Point endPoint)
{
StartPoint = startPoint;
EndPoint = endPoint;
}
public float Length()
{
float dx = EndPoint.X - StartPoint.X;
float dy = EndPoint.Y - StartPoint.Y;
return (float)Math.Sqrt(dx * dx + dy * dy);
}
}
//射线的定义
public class Ray
{
public Point Origin { get; set; } // 射线起点
public Point Direction { get; set; } // 射线方向向量
public Ray(Point origin, Point direction)
{
Origin = origin;
Direction = direction;
}
// 判断当前对象是否为射线
public bool IsRay()
{
// 如果方向向量为零向量,则不是射线
if (Direction.X == 0 && Direction.Y == 0)
{
return false;
}
return true;
}
}
//三角形的定义
public class Triangle
{
public Point A { get; set; }
public Point B { get; set; }
public Point C { get; set; }
public LineSegment L1 { get; private set; }
public LineSegment L2 { get; private set; }
public LineSegment L3 { get; private set; }
public List<LineSegment> lineSegments { get; private set; }
public Triangle(Point a, Point b, Point c)
{
A = a;
B = b;
C = c;
lineSegments = new List<LineSegment>();
L1 =new LineSegment(A, B);
L2=new LineSegment(B, C);
L3=new LineSegment(C, A);
lineSegments.Add(L1);
lineSegments.Add(L2);
lineSegments.Add(L3);
}
// 判断当前对象是否为三角形
public bool IsTriangle()
{
// 如果三点共线,则不是三角形
float crossProduct = (B.X - A.X) * (C.Y - A.Y) - (B.Y - A.Y) * (C.X - A.X);
if (Math.Abs(crossProduct) < float.Epsilon)
{
return false;
}
return true;
}
public List<LineSegment> GetEdges()
{
return lineSegments;
}
}
圆的定义
public class Circle
{
private float radius;
public Circle(float radius)
{
this.radius = radius;
}
public bool IsCircle()
{
return this.radius > 0;
}
}
多边形的定义
public class Polygon
{
public Point[] Points { get; set; } // 多边形的顶点
public Polygon(Point[] points)
{
Points = points;
}
}