Guest User

ORIGINAL_Shapes2D_template

a guest
Nov 20th, 2024
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.23 KB | None | 0 0
  1. from math import atan2, cos, sin, pi
  2.  
  3. class Point2D:
  4.     """
  5.    Point 2D Class
  6.        Each object is point in the x-y plane.
  7.        Coordinates are 2 floating point numbers x and y.
  8.    """
  9.     __precision = 10
  10.  
  11.     def __init__(self, x=0, y=0):
  12.         """
  13.        Point2d Constructor
  14.            Default value is (0, 0)
  15.        """
  16.         self.__r  = (x**2 + y**2)**0.5
  17.         self.__th = atan2(y, x)
  18.    
  19.     def getX(self):
  20.         """
  21.        Get radius of equivalent polar coordinate.
  22.        """
  23.         return round(self.__r * cos(self.__th), Point2D.__precision)
  24.    
  25.     def getY(self):
  26.         """
  27.        Get radius of equivalent polar coordinate.
  28.        """
  29.         return round(self.__r * sin(self.__th), Point2D.__precision)
  30.  
  31.     def translateX(self, x):
  32.         """
  33.        Translate in the x direction
  34.        """
  35.         nx = x + self.getX()
  36.         ny = self.getY()
  37.         self.__r  = (nx**2 + ny**2)**0.5
  38.         self.__th = atan2(ny, nx)
  39.  
  40.     def translateY(self, y):
  41.         """
  42.        Translate in the y direction
  43.        """
  44.         nx = self.getX()
  45.         ny = y + self.getY()
  46.         self.__r  = (nx**2 + ny**2)**0.5
  47.         self.__th = atan2(ny, nx)
  48.  
  49.     def getRadius(self):
  50.         """
  51.        Get radius of equivalent polar coordinate.
  52.        """
  53.         return round(self.__r, Point2D.__precision)
  54.  
  55.     def getTheta(self):
  56.         """
  57.        Get angle of equivalent polar coordinate.
  58.        """
  59.         return round(self.__th, Point2D.__precision)
  60.  
  61.     def extend(self, r):
  62.         """
  63.        Increase radius by a factor of r.
  64.        """
  65.         self.__r  *= r
  66.        
  67.  
  68.     def rotate(self, th):
  69.         """
  70.        Increase angle by th radians.
  71.        """
  72.         self.__th += th
  73.  
  74.  
  75.     def getDistance(self, other):
  76.         """
  77.        Return distance between two points.
  78.        """
  79.         dx = self.getX() - other.getX()
  80.         dy = self.getY() - other.getY()
  81.         return (dx**2 + dy**2)**0.5
  82.    
  83.     def getSlope(self, other):
  84.         """
  85.        Return the slope of the line containing both points.
  86.        """
  87.         dx = self.getX() - other.getX()
  88.         dy = self.getY() - other.getY()
  89.         return dy/dx
  90.    
  91.     def getMidpoint(self, other):
  92.         """
  93.        Return a Point2D object with coordinates
  94.        equal to the midpoint of the line segment
  95.        connecting self and other.
  96.        """
  97.         dx = self.getX() + other.getX()
  98.         dy = self.getY() + other.getY()
  99.         return Point2D(dx/2.0, dy/2.0)
  100.  
  101. from copy import deepcopy
  102.  
  103. class Shape2D:
  104.     """
  105.    Shape 2D Class
  106.        Each object is shape in the x-y plane.
  107.        A shape in this context is defined as a set of points
  108.        that are connected one after the other, where the
  109.        last point is connected to the first point as well.
  110.    """
  111.     def __init__(self, points=[]):
  112.         """
  113.        Shape2D Constructor
  114.            Defaults to no points yet.
  115.        """
  116.         self._points = points
  117.         self._nsides = len(self._points)
  118.  
  119.     def set_points(self, new_points):
  120.         self._points = new_points
  121.         self._nsides = len(self._points)
  122.  
  123.     def clear_points(self):
  124.         self._points = []
  125.         self._nsides = 0
  126.  
  127.     def get_points(self):
  128.         # Uses deep copy to ensure returned copy
  129.         # does not modify original list.
  130.         return deepcopy(self._points)
  131.    
  132.     def print_points(self):
  133.         # Prints each point as (x, y)
  134.         for p in self.get_points():
  135.             print(f"({p.getX()}, {p.getY()}), ", end="")
  136.         print()
  137.         return deepcopy(self._points)
  138.    
  139.  
  140.     def copy(self):
  141.         # Returns a copy of the shape
  142.         return Shape2D(self.get_points())
  143.  
  144.     def add_point(self, new_point):
  145.         self._points.append(new_point)
  146.         self._nsides = len(self._points)
  147.  
  148.     def get_allX(self):
  149.         return [p.getX() for p in self.get_points()]
  150.    
  151.     def get_allY(self):
  152.         return [p.getY() for p in self.get_points()]
  153.  
  154.     def translateX(self, x):
  155.         """
  156.        Translate all points to the x direction
  157.        """
  158.         for i in range(self._nsides):
  159.             self._points[i].translateX(x)
  160.  
  161.     def translateY(self, y):
  162.         """
  163.        Translate all points to the y direction
  164.        """
  165.         for i in range(self._nsides):
  166.             self._points[i].translateY(y)
  167.    
  168.     def rotate(self, th):
  169.         """
  170.        Rotates all points about the origin
  171.        """
  172.         for i in range(self._nsides):
  173.             self._points[i].rotate(th)
  174.         return
  175.  
  176.     def getPerimeter(self):
  177.         """
  178.        Returns the perimeter of the shape
  179.        """
  180.         perim = 0
  181.         for i in range(self._nsides):
  182.             perim += self._points[i-1].getdistance(self._points[i])
  183.         return perim
  184.  
  185. class Triangle(Shape2D):
  186.     def __init__(self, points=[]):
  187.         """
  188.        Triangle Constructor
  189.            Defaults to [(0,0), (1,0), (0,1)].
  190.        """
  191.         self.set_points(points)
  192.         self._nsides = 3
  193.  
  194.     def set_points(self, points):
  195.         if len(points) == 3:
  196.             self._points = points
  197.         else:
  198.             print("Only Three Points Allowed, using default values")
  199.             self._points = [Point2D(0,0), Point2D(1,0), Point2D(0,1)]
  200.  
  201.  
  202. class Square(Shape2D):
  203.     def __init__(self, side=1, center=(0,0)):
  204.         """
  205.        Square Constructor
  206.            Defaults to Unit Square
  207.            centered at the origin.
  208.        """
  209.         self._points =  [Point2D(0.5,0.5), Point2D(-0.5,0.5), \
  210.                          Point2D(-0.5,-0.5), Point2D(0.5,-0.5)]
  211.         self._nsides = 4
  212.        
  213.     def scale(self, r):
  214.         """
  215.        Increases square side length by a factor of r.
  216.        Center of the square is maintained.
  217.        """
  218.         for i in range(4):
  219.             self._points[i].extend(r)
  220.        
  221.     def get_center(self):
  222.         """
  223.        Returns the center of the square.
  224.        """
  225.         return (0, 0)
  226.    
  227.     def set_center(self, c):
  228.         """
  229.        Sets the center of the square.
  230.        """
  231.         return
  232.  
  233. import matplotlib.pyplot as plt
  234. # May require `python -m pip install -U matplotlib`
  235.  
  236. class Drawing:
  237.     def __init__(self, shape_list=[]):
  238.         temp = [issubclass(type(x), Shape2D) for x in shape_list]
  239.         if False in temp:
  240.             # Check if any element of shape_list is not a Shape2D
  241.             print("Invalid list of shapes, creating empty list instead.")
  242.             self.__shape_list=[]
  243.         # Create a list member that would store the given shapes
  244.         self.__shape_list=[]
  245.        
  246.     def show(self, a=1):
  247.         fig, ax = plt.subplots()
  248.         # Plot each Shape2D in a figure
  249.  
  250.         for shape in self.__shape_list:
  251.             x_list = shape.get_allX()
  252.             y_list = shape.get_allY()
  253.             ax.plot(x_list + [x_list[0]], y_list + [y_list[0]], alpha=a)
  254.         plt.show()
  255.    
  256.     def add_shape(self, shape):
  257.         if not (issubclass(type(shape), Shape2D)):
  258.             print("Invalid Shape2D")
  259.             return
  260.         # Insert shape to list of Shape2D
  261.         self.__shape_list.append(shape)
  262.  
  263.     def clear(self):
  264.         # Remove all the Shape2D
  265.         self.__shape_list=[]
  266.    
  267.    
Advertisement
Add Comment
Please, Sign In to add comment