예제 #1
0
class GeometricShape:
    def __init__(self, *sides):
        self.sides = sides
        self.shape = None
        self._init()
    
    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)
    
    def name(self):
        self._assert_shape()
        return self.shape.name()

    def perimeter(self):
        self._assert_shape()
        return self.shape.perimeter()
    
    def area(self):
        self._assert_shape()
        return self.shape.area()

    def _assert_shape(self):
        assert (self.shape is not None), 'Not a valid geometric shape'
예제 #2
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)
예제 #3
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)
예제 #4
0
class TestRectangle:
    _instance_count = 0

    def setup_class(self):
        self.rectangle = Rectangle(5, 4)

    def test_name(self):
        rectangle = Rectangle(1, 1)
        assert rectangle.name == 'Прямоугольник_2'

    def test_area(self):
        assert self.rectangle.area == 5 * 4

    def test_angles(self):
        assert self.rectangle.angles == 4

    def test_perimeter(self):
        assert self.rectangle.perimeter == 2 * (5 + 4)

    def test_add_square(self):
        circle = Rectangle(1, 1)
        assert self.rectangle.add_square(circle) == 20 + 1

    def test_add_square_neg(self):
        not_shape = 'not_shape'
        with pytest.raises(NotShapeException):
            assert self.rectangle.add_square(not_shape) == 20
    def line_to_shape(self, line: str) -> Optional[Shape]:
        if Ellipse.is_valid_description(line):
            return Ellipse.parse_from_line(line)

        if Rectangle.is_valid_description(line):
            return Rectangle.parse_from_line(line)

        return None
예제 #6
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)
예제 #7
0
class RectangleTest(TestCase):
    """
    Defines a test case for the Rectangle class.
    """
    def setUp(self):
        """
        Create a few test objects.
        """
        self.len7wid3 = Rectangle(7, 3)
        self.len1wid6 = Rectangle(1, 6)
        self.len5wid5 = Rectangle(5, 5)

    def test_area(self):
        """
        Compare the test rectangle area computations to the actual values.
        """
        self.assertEqual(self.len7wid3.area(), 21)
        self.assertEqual(self.len1wid6.area(), 6)
        self.assertEqual(self.len5wid5.area(), 25)

    def test_perimeter(self):
        """
        Compare the test rectangle perimeter computations to the actual values.
        """
        self.assertEqual(self.len7wid3.perimeter(), 20)
        self.assertEqual(self.len1wid6.perimeter(), 14)
        self.assertEqual(self.len5wid5.perimeter(), 20)

    def test_is_square(self):
        """
        Confirm or deny if the rectangle is a square.
        """
        self.assertFalse(self.len7wid3.is_square())
        self.assertFalse(self.len1wid6.is_square())
        self.assertTrue(self.len5wid5.is_square())
예제 #8
0
    def testValidateRectangle(self):
        r1 = ShapeFactory.build("rectangle", Point(1, 1), Point(4, 1),
                                Point(4, 3), Point(1, 3))
        Rectangle.validateRectangle(r1, "Rectangle unexpectedly invalid")

        self.assertRaises(
            ShapeException, Rectangle.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, Rectangle.validateRectangle,
                          Point(1, 1), "Point is not a valid rectangle")
예제 #9
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)
예제 #10
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)
예제 #11
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)
예제 #12
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
예제 #13
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,
         )
예제 #14
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")
 def setUp(self):
     """
     Create a few test objects.
     """
     self.len7wid3 = Rectangle(7, 3)
     self.len1wid6 = Rectangle(1, 6)
     self.len5wid5 = Rectangle(5, 5)
예제 #16
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)
예제 #17
0
    def build_figure(figure):
        if figure["type"] == "point":
            return Point.build(figure)

        if figure["type"] == "circle":
            return Circle.build(figure)

        if figure["type"] == "polygon":
            return Polygon.build(figure)

        if figure["type"] == "rectangle":
            return Rectangle.build(figure)

        if figure["type"] == "square":
            return Square.build(figure)

        raise ValueError("incorrect type")
    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)
예제 #19
0
파일: main.py 프로젝트: AA122AA/paint
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])
예제 #20
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
예제 #21
0
 def testRectangle3by2(self):
     self.assertEqual('***\n***\n', str(Rectangle(3, 2)))
예제 #22
0
class GameInterface(Interface):
    attack: AttackPattern = None
    aii: ArrayInterfaceImage = None
    background_sprite: Sprite = None
    batch: Batch = None
    border: Rectangle = None
    enemy: Enemy = None
    image = None
    facecam: Facecam = None
    face_cascade = None
    foreground_sprite: Sprite = None
    fps_display: FPSDisplay = None
    keys = key.KeyStateHandler()
    player: Player = None
    projectiles: List[Projectile] = []
    powerup: Powerup = None
    scheduled_functions = tuple()

    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()

    def generate_enemy(self, dt):
        enemy_index = config.get_config('enemy')
        if enemy_index > len(enemies) - 1:
            return system.get_window().load_interface(WinInterface())

        window = system.get_window()
        self.enemy = enemies[enemy_index](self.batch, speed=100)
        self.enemy.move(window.width * 0.8, window.height / 2)
        self.enemy.next_x, self.enemy.next_y = self.enemy.x, self.enemy.y

        def on_die():
            config.set_config('enemy', config.get_config('enemy') + 1)
            clock.schedule_once(self.generate_enemy, 2)

        self.enemy.on_die = on_die

    def resize(self):
        window = system.get_window()
        scale = window.width / self.background.width
        self.background_sprite.scale = scale
        self.big_planet_sprite.scale = scale / 2
        self.far_planet_sprite.scale = scale / 2
        self.ring_planet_sprite.scale = scale / 2
        self.stars_sprite.scale = scale

        self.big_planet_sprite.x = window.width / 2
        self.big_planet_sprite.y = window.height / 2
        self.far_planet_sprite.x = window.width - self.far_planet_sprite.width
        self.far_planet_sprite.y = window.height - self.far_planet_sprite.height

        if self.image:
            self.image.x = (window.width - self.image.width) / 2
            self.image.y = (window.height - self.image.height) / 2
        self.border.x = window.width / 2 * 0.3
        self.border.y = (window.height - self.border.height) / 2

        self.generate_powerup(0)
        self.player.move(x=window.width / 2 * 0.3, y=window.height / 2)

    def on_draw(self):
        self.animate_background()
        self.background_sprite.draw()
        self.big_planet_sprite.draw()
        self.far_planet_sprite.draw()
        self.ring_planet_sprite.draw()
        self.stars_sprite.draw()
        self.border.draw()
        if self.facecam:
            img = self.facecam.read()
            img = cv.flip(img, -1)
            self.image.blit(self.border.x, self.border.y, 0)
            self.aii.view_new_array(img)
        # self.fps_display.draw()
        self.player.draw()
        self.batch.draw()
        # self.attack.draw()
        if self.enemy:
            self.enemy.draw()
        if self.powerup:
            self.powerup.forward()
            self.powerup.draw()
            if self.player.check_for_collision(self.powerup):
                self.powerup.on_collide(self.player)
                self.powerup.delete()
                self.powerup = None

    def animate_background(self):
        big_planet_sprite_depth = 3
        far_planet_sprite_depth = 10
        ring_planet_sprite_depth = 5
        stars_sprite_depth = 8

        window = system.get_window()
        self.big_planet_sprite.x = self.big_planet_sprite.x - 1 * (1 / big_planet_sprite_depth)
        if self.big_planet_sprite.x + self.big_planet_sprite.width <= 0:
            self.big_planet_sprite.x = window.width
        self.far_planet_sprite.x = self.far_planet_sprite.x - 1 * (1 / far_planet_sprite_depth)
        if self.far_planet_sprite.x + self.far_planet_sprite.width <= 0:
            self.far_planet_sprite.x = window.width
        self.ring_planet_sprite.x = self.ring_planet_sprite.x - 1 * (1 / ring_planet_sprite_depth)
        if self.ring_planet_sprite.x + self.ring_planet_sprite.width <= 0:
            self.ring_planet_sprite.x = window.width
        self.stars_sprite.x = self.stars_sprite.x - 1 * (1 / stars_sprite_depth)
        if self.stars_sprite.x + self.stars_sprite.width <= 0:
            self.stars_sprite.x = window.width

    def generate_powerup(self, dt):
        window = system.get_window()
        # roll = random.randint(1, 10)
        roll = 1
        if roll <= 3:  # 30% chance of getting a powerup
            powerup = random.choice(powerups)(batch=self.batch)
            x = random.randint(int(self.border.x), int(self.border.x + self.border.width))
            powerup.move(x=x, y=window.height)

            @powerup.movement
            def movement():
                powerup.move(powerup.x, powerup.y - powerup.calculate_speed())

            self.powerup = powerup

    def randomize_projectiles(self, dt):
        if self.enemy:
            self.enemy.attack_pattern.generate()

    def check_direction(self, dt):
        unit = 500 * dt
        if self.keys[key.DOWN]:
            if self.player.get_bot_bound() - unit >= self.border.y:
                self.player.move(self.player.x, self.player.y - unit)
        elif self.keys[key.UP]:
            if self.player.get_bot_bound() + self.player.height + unit <= self.border.y + self.border.height:
                self.player.move(self.player.x, self.player.y + unit)
                # self.player.y += unit
        if self.keys[key.LEFT]:
            if self.player.get_left_bound() - unit >= self.border.x:
                self.player.move(self.player.x - unit, self.player.y)
        elif self.keys[key.RIGHT]:
            if self.player.get_left_bound() + self.player.width + unit <= self.border.x + self.border.width:
                self.player.move(self.player.x + unit, self.player.y)
        # if self.keys[key.ESCAPE]:
        # fg_ratio = 0.4
        # bg_ratio = 0.1
        # self.foreground_sprite.x = (window.width * (1 + fg_ratio)) / 2 - self.player.x * fg_ratio
        # self.foreground_sprite.y = (window.height * (1 + fg_ratio)) / 2 - self.player.y * fg_ratio
        # self.background_sprite.x = (window.width * (1 + bg_ratio)) / 2 - self.player.x * bg_ratio
        # self.background_sprite.y = (window.height * (1 + bg_ratio)) / 2 - self.player.y * bg_ratio

    def clean(self):
        self.enemy.clean()
        if self.facecam:
            self.facecam.clean()
        print(f'Deleting {self}')
        super().clean()
예제 #23
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()
예제 #24
0
def test_error_if_not_figure():
    rectangle = Rectangle(5, 2)
    with pytest.raises(Exception):
        rectangle.add_area(object())
예제 #25
0
 def test_rectangle(self):
     r = Rectangle(2, 4)
     self.assertEqual(r.perimeter(), 12)
     self.assertEqual(r.area(), 8)
     self.assertFalse(r.is_square())
예제 #26
0
def test_rectangle_angles_equals_four():
    rectangle = Rectangle(10, 6)
    assert rectangle.get_angles() == 4
예제 #27
0
def test_rectangle_is_instance_figure():
    assert isinstance(Rectangle(5, 2), BaseShape)
예제 #28
0
def test_name_rectangle():
    rectangle = Rectangle(5, 2)
    assert rectangle.get_name() == "Rectangle"
예제 #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()
예제 #30
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)