Guest User

MY_Shapes2D_template

a guest
Nov 20th, 2024
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.21 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._side = side
  210.         self._center = Point2D(*center)
  211.         self._update_points()
  212.  
  213.     def _update_points(self):
  214.         half_side = self._side / 2
  215.         center_x, center_y = self._center.getX(), self._center.getY()
  216.         self._points = [Point2D(center_x + half_side, center_y + half_side), Point2D(center_x - half_side, center_y + half_side), Point2D(center_x - half_side, center_y - half_side), Point2D(center_x + half_side, center_y - half_side)]
  217.         self._nsides = len(self._points)
  218.  
  219.     def translateX(self, dx):
  220.         self._center.translateX(dx)
  221.         self._update_points()
  222.  
  223.     def translateY(self, dy):
  224.         self._center.translateY(dy)
  225.         self._update_points()
  226.  
  227.     def rotate(self, th):
  228.         center_x, center_y = self._center.getX(), self._center.getY()
  229.         for point in self._points:
  230.             point.translateX(-center_x)
  231.             point.translateY(-center_y)
  232.             point.rotate(th)
  233.             point.translateX(center_x)
  234.             point.translateY(center_y)
  235.  
  236.     def scale(self, r):
  237.         """
  238.        Increases square side length by a factor of r.
  239.        Center of the square is maintained.
  240.        """
  241.         self._side *= r
  242.         self._update_points()
  243.    
  244.     def get_center(self):
  245.         return (self._center.getX(), self._center.getY())
  246.    
  247.     def set_center(self, c):
  248.         dx = c[0] - self._center.getX()
  249.         dy = c[1] - self._center.getY()
  250.         self.translateX(dx)
  251.         self.translateY(dy)
  252.  
  253.     def copy(self):
  254.         return Square(self._side, (self._center.getX(), self._center.getY()))
  255.  
  256. import matplotlib.pyplot as plt
  257. # May require `python -m pip install -U matplotlib`
  258.  
  259. class Drawing:
  260.     def __init__(self, shape_list=[]):
  261.         temp = [issubclass(type(x), Shape2D) for x in shape_list]
  262.         if False in temp:
  263.             # Check if any element of shape_list is not a Shape2D
  264.             print("Invalid list of shapes, creating empty list instead.")
  265.             self.__shape_list=[]
  266.         # Create a list member that would store the given shapes
  267.         self.__shape_list=[]
  268.        
  269.     def show(self, a=1):
  270.         fig, ax = plt.subplots()
  271.         # Plot each Shape2D in a figure
  272.  
  273.         for shape in self.__shape_list:
  274.             x_list = shape.get_allX()
  275.             y_list = shape.get_allY()
  276.             ax.plot(x_list + [x_list[0]], y_list + [y_list[0]], alpha=a)
  277.         plt.show()
  278.    
  279.     def add_shape(self, shape):
  280.         if not (issubclass(type(shape), Shape2D)):
  281.             print("Invalid Shape2D")
  282.             return
  283.         # Insert shape to list of Shape2D
  284.         self.__shape_list.append(shape)
  285.  
  286.     def clear(self):
  287.         # Remove all the Shape2D
  288.         self.__shape_list=[]
  289.    
  290.    
Advertisement
Add Comment
Please, Sign In to add comment