L06- Graphics2.pdf - Pygame and Computer Graphics Part 2...

This preview shows page 1 - 9 out of 25 pages.

Pygame and Computer Graphics, Part 2
Objectives Drawable Objects Animation Collision detection 2 4/9/2020 CS172 - Drexel University
Drawable Objects In real graphics applications, there tend to be many things drawn. Each of these may be a kind of particular type of drawable object. And each type of thing must have a way for it to be drawn. Sounds like a perfect application of polymorphism, abstract base classes, and inheritance! 4/9/2020 CS172 - Drexel University 3
Drawable Objects At the very least, all of our objects should have a location and a method to draw onto a surface. So let’s start off with an abstract base class that has a location for its object and requires others who derive from it to implement a draw method We may want to have more methods in our public interface 4 4/9/2020 CS172 - Drexel University
Drawable Objects import abc class Drawable(metaclass = abc.ABCMeta): def __init__(self, x = 0, y = 0): self.__x = x self.__y = y def getLocation(self): return (self.__x, self.__y) def setLocation(self, point): self.__x = point[0] self.__y = point[1] @abc.abstractmethod def draw(self,surface): pass 5 4/9/2020 CS172 - Drexel University
Drawable Derived Object Now let’s create a class that: derives from Drawable is used to store (and render) a house object (as a rectangle and triangle) at a specified location and in a specified color. 6 4/9/2020 CS172 - Drexel University
Drawable Derived Object class House(Drawable): def __init__(self, x = 0, y = 0, color = (0,0,0)): Drawable.__init__(self, x, y) self.__color = color def draw(self, surface): location = self.getLocation() pygame.draw.rect(surface, self.__color, [location[0]-15, location[1]-10, 30, 20]) pygame.draw.polygon(surface, self.__color, [(location[0]-15, location[1]-10), \ (location[0]+15, location[1]-10), (location[0], location[1]-20)]) 7 4/9/2020 CS172 - Drexel University
Main Script In our main program we can have a list of Drawable objects, appending new objects as needed.

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture