Ejemplo n.º 1
0
    def testValidConstruction(self):
        p1 = Point(1, 3)
        p2 = Point(5, 3)
        p3 = Point(5, 1)
        p4 = Point(1, 1)
        r1 = Rectangle(p1, p2, p3, p4)

        self.assertEqual(p1, r1.point1)
        self.assertEqual(p2, r1.point2)
        self.assertEqual(p3, r1.point3)
        self.assertEqual(p4, r1.point4)

        l1 = Line(-3, 1, 1, 1)
        l2 = Line(1, 1, 1, -5)
        l3 = Line(1, -5, -3, -5)
        l4 = Line(-3, -5, -3, 1)
        r2 = Rectangle(l1, l2, l3, l4)

        self.assertEqual(l1, r2.line1)
        self.assertEqual(l2, r2.line2)
        self.assertEqual(l3, r2.line3)
        self.assertEqual(l4, r2.line4)

        r3 = Rectangle(-.8, .4, 0, 2, .8, 1.6, 0, 0)
        self.assertEqual(-.8, r3.point1.x)
        self.assertEqual(.4, r3.point1.y)
        self.assertEqual(0, r3.point2.x)
        self.assertEqual(2, r3.point2.y)
        self.assertEqual(.8, r3.point3.x)
        self.assertEqual(1.6, r3.point3.y)
        self.assertEqual(0, r3.point4.x)
        self.assertEqual(0, r3.point4.y)
 def setUp(self):
     """
     Create a few test objects.
     """
     self.len7wid3 = Rectangle(7, 3)
     self.len1wid6 = Rectangle(1, 6)
     self.len5wid5 = Rectangle(5, 5)
Ejemplo n.º 3
0
    def testComputeHeight(self):
        r1 = Rectangle(0, 1, 1, 1, 1, 0, 0, 0)
        self.assertAlmostEqual(1, r1.computeHeight(), places=4)

        r2 = Rectangle(-2, 2, 3, 2, 3, 0, -2, 0)
        self.assertAlmostEqual(2, r2.computeHeight(), places=4)

        r3 = Rectangle(-.8, .4, 0, 2, .8, 1.6, 0, 0)
        self.assertAlmostEqual(.8944, r3.computeHeight(), places=4)
Ejemplo n.º 4
0
    def testComputeWidth(self):
        r1 = Rectangle(0, 1, 1, 1, 1, 0, 0, 0)
        self.assertAlmostEqual(1, r1.computeWidth(), places=4)

        r2 = Rectangle(-2, 2, 3, 2, 3, 0, -2, 0)
        self.assertAlmostEqual(5, r2.computeWidth(), places=4)

        r3 = Rectangle(-.8, .4, 0, 2, .8, 1.6, 0, 0)
        self.assertAlmostEqual(1.7889, r3.computeWidth(), places=4)
Ejemplo n.º 5
0
 def _init(self):
     self.n = len(self.sides)
     assert (self.n < 4), 'No support for sides > 3'
     if self.n == 3:
         self.shape = Triangle(*self.sides)
     elif self.n == 2:
         self.shape = Rectangle(*self.sides)
Ejemplo n.º 6
0
def get_rectangles(filename):
    """
    Read in from the JSON file supplied and create
    a list of rectangles based on the input data.
    This function is a generator.
    """
    with open(filename, 'r') as handle:
        try:
            data = json.load(handle)
        except json.decoder.JSONDecodeError as error:
            print(error)
            raise

    # Manually iterate over the JSON dictionaries in the list
    # of rectangles. Create a new Rectangle object for each one
    # and add it to the list.
    rectangle_objects = []
    for rect in data['rectangle_list']:
        length = rect['length']
        width = rect['width']
        new_rectangle = Rectangle(length, width)
        rectangle_objects.append(new_rectangle)

    # Return the list of Rectangle objects
    return rectangle_objects
Ejemplo n.º 7
0
    def testMove(self):
        r1 = Rectangle(-.8, .4, 0, 2, .8, 1.6, 0, 0)

        r1.move(3, 4)
        self.assertAlmostEqual(2.2, r1.point1.x)
        self.assertAlmostEqual(4.4, r1.point1.y)
        self.assertAlmostEqual(3, r1.point2.x)
        self.assertAlmostEqual(6, r1.point2.y)
        self.assertAlmostEqual(3.8, r1.point3.x)
        self.assertAlmostEqual(5.6, r1.point3.y)
        self.assertAlmostEqual(3, r1.point4.x)
        self.assertAlmostEqual(4, r1.point4.y)

        r1.move(-.234, -1.987)
        self.assertAlmostEqual(1.966, r1.point1.x)
        self.assertAlmostEqual(2.413, r1.point1.y)
        self.assertAlmostEqual(2.766, r1.point2.x)
        self.assertAlmostEqual(4.013, r1.point2.y)
        self.assertAlmostEqual(3.566, r1.point3.x)
        self.assertAlmostEqual(3.613, r1.point3.y)
        self.assertAlmostEqual(2.766, r1.point4.x)
        self.assertAlmostEqual(2.013, r1.point4.y)

        r1.move(.234, 1.987)
        self.assertAlmostEqual(2.2, r1.point1.x)
        self.assertAlmostEqual(4.4, r1.point1.y)
        self.assertAlmostEqual(3, r1.point2.x)
        self.assertAlmostEqual(6, r1.point2.y)
        self.assertAlmostEqual(3.8, r1.point3.x)
        self.assertAlmostEqual(5.6, r1.point3.y)
        self.assertAlmostEqual(3, r1.point4.x)
        self.assertAlmostEqual(4, r1.point4.y)
Ejemplo n.º 8
0
def test_rectangle():
    """
    Defines tests on some specific rectangle objects.
    """
    len7wid3 = Rectangle(7, 3)
    len1wid6 = Rectangle(1, 6)
    len5wid5 = Rectangle(5, 5)

    # Test areas, perimeters, and whether they are squares
    assert len7wid3.area() == 21
    assert len1wid6.area() == 6
    assert len5wid5.area() == 25
    assert len7wid3.perimeter() == 20
    assert len1wid6.perimeter() == 14
    assert len5wid5.perimeter() == 20
    assert not len7wid3.is_square()
    assert not len1wid6.is_square()
    assert len5wid5.is_square()
Ejemplo n.º 9
0
 def __init__(self, src: str, background: tuple = None, speed: Union[int, float] = 1, damage: Union[int, float] = 1,
              acceleration: Union[int, float] = 0, animated: bool = False, animation_rows: int = None,
              animation_columns: int = None,
              animation_item_width: int = None, animation_item_height: int = None, animation_period: float = 0.1,
              animation_main_frame: int = 0, *args, **kwargs) -> None:
     """
     :param src:                     File of the image to load
     :param background:              A tuple representing RGBA values for the background
     :param speed:                   Speed at which the projectile will move
     :param damage:                  Damage the projectile will deal
     :param acceleration:            Acceleration in m/s^2
     :param animated:                Flag saying if the projectile uses an animation
     :param animation_rows:          The number of rows in the animation sequence source
     :param animation_columns:       The number of columns in the animation sequence source
     :param animation_item_width:    The width of each frame of the animation in the source
     :param animation_item_height:   The height of each frame in the source
     :param animation_period:        Time to show each frame
     :param animation_main_frame:    The frame in which the hitbox bounds will be calculated
     :param args:
     :param kwargs:
     """
     if animated:
         image = load(src)
         image_seq = ImageGrid(image, rows=animation_rows, columns=animation_columns,
                               item_width=animation_item_width, item_height=animation_item_height)
         image_texture = TextureGrid(image_seq)
         img = Animation.from_image_sequence(image_texture[0:], period=animation_period, loop=True)
         # self.src =
         image_array = cv.imread(src)
         x1 = animation_item_width * animation_main_frame
         x2 = x1 + animation_item_width
         self.np = image_array[:, x1:x2]  # The numpy array used for the collision test will be the slice
     else:
         img = load(src)
         self.np = cv.imread(src)  # The whole image will be read
     self.src = img
     self.background = background
     self.speed = speed
     self.acceleration = acceleration
     self.damage = damage
     super().__init__(img, *args, **kwargs)
     self.radians = 0
     # self.anchor
     if animated:
         for frame in self.image.frames:
             frame.image.anchor_x = image.width / animation_columns / 2
             frame.image.anchor_y = image.height / animation_rows / 2
     else:
         self.image.anchor_x = self.image.width / 2
         self.image.anchor_y = self.image.height / 2
     self.init_time = time.time()
     self.update(x=self.x, y=self.y)
     self.refresh_threshold()
     if self.background:
         self.rectangle = Rectangle(x=self.get_left_bound(), y=self.get_bot_bound(), width=self.width,
                                    height=self.height, color=self.background)
Ejemplo n.º 10
0
    def testValidateRectangle(self):
        r1 = Rectangle(1, 1, 4, 1, 4, 3, 1, 3)
        Validator.validateRectangle(r1, "Rectangle unexpectedly invalid")

        self.assertRaises(
            ShapeException, Validator.validateRectangle,
            "(1, 1, 4, 1, 4, 3, 1, 3)",
            "String \'(1, 1, 4, 1, 4, 3, 4, 3)\' is not a valid rectangle")
        self.assertRaises(ShapeException, Validator.validateRectangle,
                          Point(1, 1), "Point is not a valid rectangle")
Ejemplo n.º 11
0
    def testInvalidConstruction(self):
        p1 = Point(1, 3)
        p2 = Point(5, 3)
        p3 = Point(5, 1)
        p4 = Point(1, 1)
        r1 = Rectangle(p1, p2, p3, p4)
        self.assertRaises(ShapeException, Square, p1, p2, p3, p4)

        l1 = Line(-3, 1, 1, 1)
        l2 = Line(1, 1, 1, -3)
        l3 = Line(1, -3, -3, -3)
        l4 = Line(-3, -3, -3, 2)
        self.assertRaises(ShapeException, Square, l1, l2, l3, l4)

        self.assertRaises(ShapeException, Square, -1, 0, 0, 2, 1, 0, 0, -2)
Ejemplo n.º 12
0
 def __init__(self,
              width: int,
              height: int = 0,
              multiline: bool = False,
              dpi: object = None,
              batch: Batch = None,
              group: Group = None,
              wrap_lines: bool = True,
              x: int = 0,
              y: int = 0,
              underlined: bool = True,
              caret_color: tuple = (0, 0, 0),
              numbers_only: bool = False,
              font_name=None,
              font_size=None,
              font_color=(255, 255, 255, 2555),
              max_chars=0) -> None:
     self.document = FormattedDocument()
     self.layout = IncrementalTextLayout(self.document, width, height,
                                         multiline, dpi, batch, group,
                                         wrap_lines)
     self.numbers_only = numbers_only
     self.style['color'] = font_color
     self.max_chars = max_chars
     if font_name:
         self.style['font_name'] = font_name
     if font_size:
         self.style['font_size'] = font_size
     self.reset_style()
     if not height:
         # If the dev didn't specify a height, make the height equal to the height of the font
         font = pyglet.font.load(
             font_name or self.document.get_style('font'), font_size
             or self.document.get_style('font_size'))
         self.height = font.ascent - font.descent
     self._hover_cursor = self.get_window().CURSOR_TEXT
     super().__init__(self.layout, color=caret_color)
     # TODO: Allow the dev to specify how x and y are treated
     self.x = x - self.width // 2
     self.y = y - self.height // 2
     if underlined:
         self.underline = Rectangle(
             x=self.x,
             y=self.y,
             width=self.width,
             height=1,
         )
    def add_shape(self, x: int, y: int) -> Shape:
        width = self.width_box.get()
        color = self.color_btn["bg"]
        background = self.background_btn["bg"]

        shape_type = self.type_box.get()

        if shape_type == "Ellipse":
            r1 = 10
            r2 = 10

            return Ellipse(x - r1, y - r2, r1, r2, width, color, background)

        if shape_type == "Rectangle":
            w = 20
            h = 20

            return Rectangle(x - w, y - h, w, h, width, color, background)
Ejemplo n.º 14
0
def paint(canvas):
    text = read_file()
    for line in text:
        if "rcl" in line or "va" in line:
            prop = line.split(", ")
            Oval(canvas, prop[1], prop[2], prop[3], prop[4], prop[5], prop[6],
                 prop[7])
        elif "ua" in line or "rect" in line:
            prop = line.split(", ")
            Rectangle(canvas, prop[1], prop[2], prop[3], prop[4], prop[5],
                      prop[6], prop[7])
        elif "tri" in line:
            prop = line.split(", ")
            Triangle(canvas, prop[1], prop[2], prop[3], prop[4], prop[5],
                     prop[6], prop[7], prop[8], prop[9])
        elif "in" in line:
            prop = line.split(", ")
            Line(canvas, prop[1], prop[2], prop[3], prop[4], prop[5], prop[6])
        elif "arc" in line:
            prop = line.split(", ")
            Arc(canvas, prop[1], prop[2], prop[3], prop[4], prop[5], prop[6],
                prop[7], prop[8], prop[9])
Ejemplo n.º 15
0
import pyglet
from game_objects.projectile import Projectile
from shapes.rectangle import Rectangle

# image = cv2.imread('projectiles/minecraft_sword.png')
window = pyglet.window.Window(fullscreen=True)
projectile = Projectile(src='projectiles/minecraft_sword.png')
projectile.x = window.width / 2
projectile.y = window.height / 2
rectangle = Rectangle(x=projectile.x,
                      y=projectile.y,
                      width=projectile.width,
                      height=projectile.height,
                      color=(255, 255, 255, 255))
rectangle.x -= rectangle.width / 2
rectangle.y -= rectangle.height / 2


@window.event
def on_draw():
    window.clear()
    rectangle.draw()
    projectile.draw()


# for row in image:
#     for cell in row:
#         print(cell)

if __name__ == '__main__':
    pyglet.app.run()
Ejemplo n.º 16
0
 def test_rectangle(self):
     r = Rectangle(2, 4)
     self.assertEqual(r.perimeter(), 12)
     self.assertEqual(r.area(), 8)
     self.assertFalse(r.is_square())
Ejemplo n.º 17
0
def test_rectangle_angles_equals_four():
    rectangle = Rectangle(10, 6)
    assert rectangle.get_angles() == 4
Ejemplo n.º 18
0
def test_rectangle_is_instance_figure():
    assert isinstance(Rectangle(5, 2), BaseShape)
Ejemplo n.º 19
0
def test_name_rectangle():
    rectangle = Rectangle(5, 2)
    assert rectangle.get_name() == "Rectangle"
Ejemplo n.º 20
0
def test_rectangles_equals_area_after_add_area():
    rectangle_1 = Rectangle(5, 2)
    triangle_2 = Triangle(6, 3)
    assert rectangle_1.add_area(triangle_2) == triangle_2.add_area(rectangle_1)
Ejemplo n.º 21
0
from shapes.ellipse import Ellipse
from shapes.circle import Circle
from shapes.rectangle import Rectangle
from shapes.square import Square
from shape_list.shape_list import ShapeList
from color.color import Color

shape_list = ShapeList()

try:
    shape_list.append(1)
except TypeError:
    print('Only shape append support')

shape_list.append(Circle(5, Color.BLUE))
shape_list.append(Rectangle(2, 3, Color.RED))
shape_list.append(Square(5, Color.BLUE))
shape_list.append(Ellipse(2, 3, Color.GREEN))

print(shape_list)
print(shape_list.sorted_shapes_areas(Color.BLUE))
print(Ellipse(4, 5, Color.BLUE).__hash__())
print(Ellipse(4, 5, Color.RED).__hash__())
print(Ellipse(5, 4, Color.BLUE).__hash__())
a = Circle(4, Color.BLUE)
d = Circle(4, Color.BLUE)
b = Circle(4, Color.RED)
c = Ellipse(4, 5, Color.BLUE)
print(a == c)  #False
print(a == b)  #False
print(a == d)  #True
Ejemplo n.º 22
0
# facecam = Facecam(face_cascade, src='ACM App.mp4').start()
img = cv2.imread('faces/four.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
aii = ArrayInterfaceImage(img, 'BGR')
soul = pyglet.image.load('chihiro.png')
soul_sprite = pyglet.sprite.Sprite(soul, x=0, y=0)
image = aii.texture
window = pyglet.window.Window(vsync=False)
window.maximize()
# window.height = image.height
# window.width = image.width
fps_display = FPSDisplay(window)
box = Rectangle(x=0, y=0, width=100, height=100)


@window.event
def on_draw():
    window.clear()
    image.blit(0, 0, 0)
    # img = facecam.read()
    aii.view_new_array(img)
    fps_display.draw()
    soul_sprite.draw()


if __name__ == '__main__':
    count = 0
    timer = time.time()
Ejemplo n.º 23
0
    def run_command(self, input_list):
        """
    Checks the arguments of the input list are within the command list and run the associated command.\n
    Parameters: (1) user input parameters
    """
        # Create clear console function
        clear_console = lambda: os.system('cls')

        # Create command list
        command_list = [
            "rectangle", "square", "circle", "add", "shift", "move", "scale",
            "menu", "display", "exit"
        ]

        # Create parameters list
        parameters = list(input_list)
        parameters.pop(0)  # remove first element
        parameters = [int(i) for i in parameters]

        # Check if command is in command list
        if input_list[0] not in command_list:
            print(
                "First argument is invalid, check correct spelling provided!")

        # Create Rectangle
        elif input_list[0] == "rectangle" and len(input_list) == 5:

            # Set Rectangle object, store shape and return output
            r = Rectangle(parameters[0], parameters[1], parameters[2],
                          parameters[3])
            self._shapes[self._idx] = r
            r.display_stats()

            # Update shape index
            self._idx += 1

            print()
            print("Input the command 'menu' for the list of commands.")

        # Create Square
        elif input_list[0] == "square" and len(input_list) == 4:

            # Set Square object, store shape and return output
            s = Square(parameters[0], parameters[1], parameters[2])
            self._shapes[self._idx] = s
            s.display_stats()

            # Update shape index
            self._idx += 1

            print()
            print("Input the command 'menu' for the list of commands.")

        # Create Circle
        elif input_list[0] == "circle" and len(input_list) == 4:

            # Set Circle object, store shape and return output
            c = Circle(parameters[0], parameters[1], parameters[2])
            self._shapes[self._idx] = c
            c.display_stats()

            # Update shape index
            self._idx += 1

            print()
            print("Input the command 'menu' for the list of commands.")

        # Move or scale a shape
        elif (input_list[0] == "move"
              or input_list[0] == "scale") and len(input_list) == 4:

            # Check shape parameter is correct
            if parameters[0] not in self._shapes:
                print("Shape doesn't exist! Try a different index.")
            else:
                print("---------------------------------")
                print(f"Shape Number: {parameters[0]} updated")
                print("---------------------------------")

                # Move the selected shape
                if input_list[0] == "move":
                    self._shapes[parameters[0]].move(parameters[1],
                                                     parameters[2])

                # Scale the selected shape
                elif input_list[0] == "scale":
                    self._shapes[parameters[0]].scale(parameters[1],
                                                      parameters[2])

                # Display shape statistics
                self._shapes[parameters[0]].display_stats()

                print()
                print("Input the command 'menu' for the list of commands.")

        # Display add menu
        elif input_list[0] == "add":
            clear_console()
            self.add_menu()

        # Display shift menu or shapes
        elif input_list[0] == "shift" or input_list[0] == "display":

            # Check shape size
            if len(self._shapes) == 0:
                print("No shapes have been created! Create a shape first.")
            else:
                clear_console()

                # Show shift menu
                if input_list[0] == "shift":
                    self.shift_menu()

                # Display shape list
                for key, shape in self._shapes.items():
                    print("------------------------------")
                    print(f"Shape Number: {key}")
                    print("------------------------------")
                    shape.display_stats()
                    print()

                # Show additional print
                if input_list[0] == "display":
                    print("Input the command 'menu' for the list of commands.")

        # Display menu
        elif input_list[0] == "menu":
            clear_console()
            self.main_menu()

        # Exit the program
        elif input_list[0] == "exit":
            self.exit_program()

        # Check arguments length
        else:
            print(
                f"Incorrect argument length. Length provided: {len(input_list)}"
            )

        # Create extra space
        print()
Ejemplo n.º 24
0
 def testRectangle0by0(self):
     self.assertEqual('', str(Rectangle(0, 0)))
Ejemplo n.º 25
0
 def setup_class(self):
     self.rectangle = Rectangle(5, 4)
Ejemplo n.º 26
0
def test_error_if_not_figure():
    rectangle = Rectangle(5, 2)
    with pytest.raises(Exception):
        rectangle.add_area(object())
Ejemplo n.º 27
0
 def testRectangle1by1(self):
     self.assertEqual('*\n', str(Rectangle(1, 1)))
Ejemplo n.º 28
0
    def __init__(self,
                 text: str = '',
                 font_name: str = None,
                 font_size: int = None,
                 bold: bool = False,
                 italic: bool = False,
                 color: tuple = (255, 255, 255, 255),
                 x: int = 0,
                 y: int = 0,
                 width: int = None,
                 height: int = None,
                 anchor_x: str = 'left',
                 anchor_y: str = 'baseline',
                 align: str = 'left',
                 multiline: bool = False,
                 dpi: float = None,
                 batch: Batch = None,
                 group: Group = None,
                 padding: tuple = (0, 0, 0, 0)) -> None:
        """

        :param text:        The text to be displayed on the button
        :param font_name:   Name of the font to be used
        :param font_size:   Font size
        :param bold:        Sets the font style to bold if true
        :param italic:      Sets the font style to italic if true
        :param color:       Sets the color of the text
        :param x:           The x-coordinate with respect to the origin (0, 0
        :param y:
        :param width:
        :param height:
        :param anchor_x:
        :param anchor_y:
        :param align:
        :param multiline:
        :param dpi:
        :param batch:
        :param group:
        :param padding:
        """
        if len(padding) == 0:
            # No padding is supported, and nothing special will happen
            pass
        elif len(padding) == 1:
            # If only one padding value is supplied, it will be applied to all sides
            padding = (padding[0], ) * 4
        elif len(padding) == 2:
            # If only two values (a, b) are supplied, a will be applied to top and bottom padding,
            # and b will be applied to left and right padding,
            # as  (a, b, a, b)
            padding = padding[0], padding[1], padding[0], padding[1]
        elif len(padding) == 4:
            pass
        else:
            # No other padding combination will work, so throw an error
            raise ValueError
        super().__init__(text, font_name, font_size, bold, italic, color,
                         x + padding[3], y + padding[2], width, height,
                         anchor_x, anchor_y, align, multiline, dpi, batch,
                         group)  # Allow the Label superclass to __init__

        self.padding = padding

        # width of the label + padding on left and right
        self.width = self.content_width + self.padding[3] + self.padding[1]

        # height of the label + padding on the bottom and top
        self.height = self.padding[2] + self.content_height + self.padding[0]

        # The background color
        self.rectangle = Rectangle(x=x,
                                   y=y,
                                   width=self.width,
                                   height=self.height)
Ejemplo n.º 29
0
    def __init__(self):
        super().__init__()
        window = system.get_window()
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        base_path = os.path.join('images', 'space_background_pack', 'layers')

        self.background = load(os.path.join(base_path, 'parallax-space-background.png'))
        self.background_sprite = Sprite(self.background)
        big_planet = load(os.path.join(base_path, 'parallax-space-big-planet.png'))
        self.big_planet_sprite = Sprite(big_planet)
        far_planet = load(os.path.join(base_path, 'parallax-space-far-planets.png'))
        self.far_planet_sprite = Sprite(far_planet)
        ring_planet = load(os.path.join(base_path, 'parallax-space-ring-planet.png'))
        self.ring_planet_sprite = Sprite(ring_planet)
        self.ring_planet_sprite.x = 100
        self.ring_planet_sprite.y = 100
        stars = load(os.path.join(base_path, 'parallax-space-stars.png'))
        self.stars_sprite = Sprite(stars)
        self.scheduled_functions = (
            (self.randomize_projectiles, 2),
            (self.check_direction, 1 / 120),
            (self.generate_powerup, 20)
        )

        if config.get_config('control') == 1:
            self.face_cascade = cv.CascadeClassifier(
                'venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
            self.facecam = Facecam(face_cascade=self.face_cascade).start()
            self.aii = ArrayInterfaceImage(self.facecam.read(), 'BGR')
            self.image = self.aii.texture

            @self.facecam.event('on_face_move')
            def follow_face(x, y, width, height):
                # Need to flip things first to work
                x = self.image.width - x
                y = self.image.height - y
                new_x = self.border.x + x - width // 2
                new_y = self.border.y + y - height // 2
                self.player.move(new_x, new_y)

            self.scheduled_functions = (
                (self.randomize_projectiles, 2),
                (self.generate_powerup, 20),
            )

            window.push_handlers(self.facecam)

        self.player = Player(src='images/ufo.png')
        self.border = Rectangle(
            width=(500 if not self.image else self.image.width) + 10,
            height=(500 if not self.image else self.image.height) + 10,
            color=(0, 0, 0, 127)
        )
        self.player.scale = 1.2
        self.batch = Batch()
        self.projectiles: List[Projectile] = []
        window.push_handlers(self.keys)

        def pause_game(symbol, modifiers):
            if symbol == key.ESCAPE:
                self.enemy.running = not self.enemy.running
                self.enemy.attack_pattern.running = not self.enemy.attack_pattern.running
                self.player.running = not self.player.running

        window.on_key_press = pause_game

        for func, interval in self.scheduled_functions:
            clock.schedule_interval(func, interval)
        self.fps_display = FPSDisplay(window)
        self.generate_enemy(0)
        self.resize()
Ejemplo n.º 30
0
 def testRectangle3by2(self):
     self.assertEqual('***\n***\n', str(Rectangle(3, 2)))