CSC352 StrangeShape.py
--D. Thiebaut 20:53, 24 February 2010 (UTC)
#! /usr/bin/python
# strangeSurface.py
# D. Thiebaut
#
import random
import math
import pickle
class Point:
"""A simple container for the x & y coordinates of a point"""
def __init__(self, h, v):
self.h = h
self.v = v
class StrangeShape:
"""The strange shape we need to measure the area of.
The main function is isInside( point ) which returns True
if the point is inside the surface, False otherwise."""
def __init__( self ):
"""constructor: generate the polygone"""
self.polygon = self.generateStrangePoly()
def generateStrangePoly( self ):
return pickle.loads("""(lp0
(F0.10000000000000001
F0.10000000000000001
tp1
a(F0.90000000000000002
F0.10000000000000001
tp2
a(F0.5
F0.20000000000000001
tp3
a(F0.90000000000000002
F0.5
tp4
a(F0.90000000000000002
F0.90000000000000002
tp5
a(F0.10000000000000001
F0.90000000000000002
tp6
a.
""")
def Angle2D(self, x1, y1, x2, y2):
"""utility function"""
theta1 = math.atan2(y1, x1)
theta2 = math.atan2(y2, x2)
dtheta = theta2 - theta1
while dtheta > math.pi:
dtheta -= 2.0 * math.pi
while dtheta < -math.pi:
dtheta += 2.0 * math.pi
return dtheta
def isInside( self, p ):
"""the test function. Returns True if point inside surface"""
angle = 0.0
n = len(self.polygon)
for i, (h, v) in enumerate( self.polygon ):
p1 = Point(h - p.h, v - p.v)
h, v = self.polygon[(i + 1) % n]
p2 = Point(h - p.h, v - p.v)
angle += self.Angle2D(p1.h, p1.v, p2.h, p2.v);
if abs(angle) < math.pi:
return False
return True
# ----------------------------------------------------------------------------
def main():
shape = StrangeShape()
while True:
print "enter a point's coordinates: "
p = Point( input( "x> " ), input( "y> " ) )
if shape.isInside( p ):
print "+ Point is inside"
else:
print "- Point is outside"
main()