unit rectangles; {$MODE OBJFPC} // this could be used a lot more. interface type TCoordinate = Integer; TRectangleP = ^TRectangle; TRectangle = object LeftTop : record X : TCoordinate; Y : TCoordinate; end; RightBottom : record X : TCoordinate; Y : TCoordinate; end; constructor Init; function Intersect(const bRectangle : TRectangle) : TRectangleP; procedure IntersectM(const bRectangle : TRectangle); procedure AssignFrom(const bRectangle : TRectangle); end; implementation function Max(aA, aB : TCoordinate) : TCoordinate; inline; begin if aA < aB then Result := aA else Result := aB; end; function Min(aA, aB : TCoordinate) : TCoordinate; inline; begin if aA > aB then Result := aA else Result := aB; end; constructor TRectangle.Init; begin LeftTop.X := 0; LeftTop.Y := 0; RightBottom.X := 0; RightBottom.Y := 0; end; function TRectangle.Intersect(const bRectangle : TRectangle) : TRectangleP; begin Result := New(TRectangleP, Init); Result^.AssignFrom(Self); Result^.IntersectM(bRectangle); end; procedure TRectangle.IntersectM(const bRectangle : TRectangle); begin Self.LeftTop.X := Max(Self.LeftTop.X, bRectangle.LeftTop.X); Self.LeftTop.Y := Max(Self.LeftTop.Y, bRectangle.LeftTop.Y); Self.RightBottom.X := Min(Self.RightBottom.X, bRectangle.RightBottom.Y); Self.RightBottom.Y := Min(Self.RightBottom.Y, bRectangle.RightBottom.Y); end; procedure TRectangle.AssignFrom(const bRectangle : TRectangle); begin Self.LeftTop.X := bRectangle.LeftTop.X; Self.LeftTop.Y := bRectangle.LeftTop.Y; Self.RightBottom.X := bRectangle.RightBottom.X; Self.RightBottom.Y := bRectangle.RightBottom.Y; end; end.