Class: Geometry::Polygon

Inherits:
Struct
  • Object
show all
Defined in:
lib/geometry/polygon.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#verticesObject

Returns the value of attribute vertices

Returns:

  • (Object)

    the current value of vertices


2
3
4
# File 'lib/geometry/polygon.rb', line 2

def vertices
  @vertices
end

Instance Method Details

#areaObject


25
26
27
28
29
30
31
32
33
34
# File 'lib/geometry/polygon.rb', line 25

def area
  sum = 0.0
  (0..vertices.length-1).each do |i|
    a = vertices[i-1]
    b = vertices[i]

    sum = sum + ((a.x * b.y) - (a.y * b.x))
  end
  (sum/2).abs
end

#bounding_boxObject


13
14
15
16
17
18
# File 'lib/geometry/polygon.rb', line 13

def bounding_box
  leftbottom = Point vertices.map(&:x).min, vertices.map(&:y).min
  righttop = Point vertices.map(&:x).max, vertices.map(&:y).max
  
  BoundingBox.new leftbottom, righttop
end

#contains?(point) ⇒ Boolean

Returns:

  • (Boolean)

20
21
22
23
# File 'lib/geometry/polygon.rb', line 20

def contains?(point)
  point_in_polygon = PointInPolygon.new(point, self)
  point_in_polygon.inside? || point_in_polygon.on_the_boundary?
end

#edgesObject


3
4
5
6
7
8
9
10
11
# File 'lib/geometry/polygon.rb', line 3

def edges
  edges = []

  1.upto(vertices.length - 1) do |vertex_index|
    edges << Segment.new(vertices[vertex_index - 1], vertices[vertex_index])
  end

  edges << Segment.new(vertices.last, vertices.first)
end