Esempio n. 1
0
 def get_orientation(self):
     if isinstance(self._hvbox, HBox):
         return Vector(1, 0)
     elif isinstance(self._hvbox, VBox):
         return Vector(0, -1)
     else:
         raise NotImplementedError
Esempio n. 2
0
    def _update_vertex_list(self):
        if self._vertex_list is None:
            return

        texture = self._image.get_texture()

        # Figure out which texture coordinates are bound to which vertices.  
        # This is not always an intuitive mapping, because textures can be 
        # rotated by changing which texture coordinates are bound to which 
        # vertices.  The in-line diagram shows which vertex is represented by 
        # each variable in the case that the image hasn't been rotated.

        a = Vector(*texture.tex_coords[0:2])     #   D┌───┐C
        b = Vector(*texture.tex_coords[3:5])     #    │   │
        c = Vector(*texture.tex_coords[6:8])     #    │   │
        d = Vector(*texture.tex_coords[9:11])    #   A└───┘B

        # The given image must have a power-of-two size in each dimension being 
        # tiled.  This is because OpenGL internally requires that textures have 
        # power-of-two dimensions.  When pyglet loads an image that doesn't 
        # have the right dimensions, it creates a properly dimensioned texture 
        # big enough to hold the image, sets texture coordinates to indicate 
        # where in that texture the actual image is, and uses that information 
        # to hide the extra space.
        #
        # However, tiling the image requires using the whole texture in each  
        # dimension being tiled.  If the given image doesn't have a power-of- 
        # two size in that dimension, this extra space would be rendered.

        if self._htile:
            if not _is_power_of_two(self._image.width):
                raise UsageError("image is {self._image.width} px wide; can only tile images with power-of-two dimensions")
            w = self._rect.width / self._image.width
        else:
            w = a.get_distance(b)

        if self._vtile:
            if not _is_power_of_two(self._image.height):
                raise UsageError("image is {self._image.height} px tall; can only tile images with power-of-two dimensions")
            h = self._rect.height / self._image.height
        else:
            h = a.get_distance(d)

        A = a
        B = a + (b - a).get_scaled(w)
        C = a + (c - d).get_scaled(w) + (c - b).get_scaled(h)
        D = a                         + (d - a).get_scaled(h)

        self._vertex_list.tex_coords = A.tuple + B.tuple + C.tuple + D.tuple
        self._vertex_list.vertices = (
                self._rect.bottom_left.tuple +
                self._rect.bottom_right.tuple +
                self._rect.top_right.tuple +
                self._rect.top_left.tuple
        )
Esempio n. 3
0
    def from_actor(cls, actor, board):
        if actor.id == 2:
            origin = Vector(0, 0)
            heading = Vector(1, 1)
            color = 'white'
        elif actor.id == 3:
            origin = Vector(board.width - 1, board.height - 1)
            heading = Vector(-1, -1)
            color = 'black'
        else:
            # There should only be two players, and their ids should be 2 and 
            # 3.  (The referee has id 1).
            raise ValueError(f"{actor!r} has unexpected id={actor.id}")

        return cls(origin, heading, color)
Esempio n. 4
0
 def __init__(self):
     super().__init__()
     self.player = None
     self.animations = []
     self.focus_point = Vector.null()
     self.show_fps = False
     self.fps_widget = pyglet.clock.ClockDisplay()
Esempio n. 5
0
    def get_position_percent(self):
        percent = Vector.null()
        ux, uy = self.unoccupied_size

        if ux != 0: percent.x = self.position.x / ux
        if uy != 0: percent.y = self.position.y / uy

        return percent
Esempio n. 6
0
    def get_position_percent(self):
        percent = Vector.null()
        ux, uy = self.unoccupied_size
        
        if ux != 0: percent.x = self.position.x / ux
        if uy != 0: percent.y = self.position.y / uy

        return percent
Esempio n. 7
0
    def pixels_to_percent(self, pixels):
        percent = Vector.null()
        ux, uy = self.unoccupied_size
        
        if ux != 0: percent.x = pixels.x / ux
        if uy != 0: percent.y = pixels.y / uy

        return percent
Esempio n. 8
0
    def pixels_to_percent(self, pixels):
        percent = Vector.null()
        ux, uy = self.unoccupied_size

        if ux != 0: percent.x = pixels.x / ux
        if uy != 0: percent.y = pixels.y / uy

        return percent
Esempio n. 9
0
    def assign_card(self, card):
        self.card = card

        # set the position of the card_image
        x, y = self.rect.center
        ext = card.get_extension(self.gui_actor)
        ext.activate(Vector(x, y))

        self.draw()
Esempio n. 10
0
    def __init__(self):
        super().__init__()

        # ``child_position`` is the vector between the bottom left corner of
        # the child's physical position (i.e. it position in it's own
        # coordinates) and it's apparent position (i.e. the position it seems
        # to be in after the translation is performed).
        self._child_position = Vector.null()
        self._translate_group = None
        self._expand_horz = True
        self._expand_vert = True
Esempio n. 11
0
    def __init__(self):
        super().__init__()

        # ``child_position`` is the vector between the bottom left corner of 
        # the child's physical position (i.e. it position in it's own 
        # coordinates) and it's apparent position (i.e. the position it seems 
        # to be in after the translation is performed).
        self._child_position = Vector.null()
        self._translate_group = None
        self._expand_horz = True
        self._expand_vert = True
Esempio n. 12
0
    def __init__(self, world):
        from vecrec import Vector
        field = world.field

        def random_position():
            return field.center + Vector.random(0.4*field.height)
        def random_velocity():
            return Vector.random(50)

        # Create a few obstacles in the same way.

        self.obstacles = [
                tokens.Obstacle(
                    Vector(
                        random.randrange(field.left + 100, field.center_x),
                        random.randrange(field.bottom + 100, field.top - 100),
                    ),
                    Vector.random(10))
                for i in range(2)
        ]

        # Create a cannon and several targets for each player and decide which 
        # side of the field each cannon should go on.

        self.targets = []
        targets_per_player = 2

        players = world.players
        num_players = len(players)
        self.cannons = []

        for i in range(num_players):
            player = players[i]
            position = Vector(
                    field.left, (i + 1) * field.height / (num_players + 1))
            self.cannons.append(
                    tokens.Cannon(player, position))

            for j in range(targets_per_player):
                x = field.width * 2/3
                y = field.height * (1 + i * targets_per_player + j) / (num_players * targets_per_player + 1)
                target = tokens.Target(
                        Vector(x, y), random_velocity(), player)
                self.targets.append(target)

        # Create the final target

        self.final_target = tokens.Target(
                Vector(field.width * 3/4, field.center_y),
                random_velocity(),
        )
        self.targets.append(self.final_target)
Esempio n. 13
0
    def __init__(self):
        self.bg_color = (0.75, 0.75, 0.75, 1.0)
        self.window_shape = Vector(400, 400)

        self.window = pyglet.window.Window()
        self.window.set_size(*self.window_shape)
        self.window.set_visible(True)
        self.window.set_caption("Cherts")
        #self.window.set_icon(
        #        pyglet.resource.image('icon_16.png'),
        #        pyglet.resource.image('icon_32.png'),
        #        pyglet.resource.image('icon_64.png'),
        #)

        self.batch = pyglet.graphics.Batch()

        self.load_images()
Esempio n. 14
0
    def __init__(self, sensitivity=3):
        Widget.__init__(self)
        BinMixin.__init__(self)

        # The panning_vector is the displacement between the bottom-left corner 
        # of this widget and the bottom-left corner of the child widget.

        self._panning_vector = Vector.null()
        self._deferred_center_of_view = None
        self.sensitivity = sensitivity

        # The stencil_group, mask_group, and visible_group members manage the 
        # clipping mask to make sure the child is only visible inside the 
        # viewport.  The panning_group member is used to translate the child in 
        # response to panning events.

        self.stencil_group = None
        self.mask_group = None
        self.visible_group = None
        self.panning_group = None
        self.mask_artist = None
Esempio n. 15
0
    def on_update_game(self, dt):
        if self.token.player is not self.actor.player:
            return

        cannon = self.token
        player = self.token.player
        world = self.token.world

        self.shot_timer -= dt
        if self.shot_timer < 0:
            self.reset_shot_timer()

            # Pick the closest target to aim at.

            def distance_to_cannon(target):
                return cannon.position.get_distance(target.position)

            if self.token.player.targets:
                target = sorted(player.targets, key=distance_to_cannon)[0]
            else:
                target = world.final_target

            # Aim in front of the target with some variance.

            aim = target.position - cannon.position
            aim += 0.0 * target.velocity
            aim += 0.05 * aim.magnitude * Vector.random()
            aim.normalize()

            velocity = cannon.muzzle_speed * aim
            position = cannon.position + 25 * aim
            bullet = tokens.Bullet(cannon, position, velocity)

            # Shoot unless we're out of bullets.

            if player.can_shoot(bullet):
                self.actor >> messages.ShootBullet(bullet)
            else:
                self.shot_timer /= 2
Esempio n. 16
0
    def do_draw_face(self):
        N = 48
        vertices = []

        for i in range(N + 2):
            direction = Vector.from_degrees(360 * i / N)
            radius = self._radius - (i % 2 * self.custom_face_border_width)
            vertex = self.rect.center + radius * direction
            vertices += vertex.tuple

        # Insert duplicate vertices at the beginning and end of the list, 
        # otherwise this triangle strip will end up connected to any other 
        # triangle strips in the scene.

        vertices = vertices[:2] + vertices + vertices[-2:]
        num_vertices = len(vertices) // 2

        color = glooey.drawing.Color.from_anything(self._color)
        colors = num_vertices * color.rgb

        # The vertex list for the face may or may not exist yet, e.g. if the 
        # clock is being drawn for the first time or was previously being 
        # hidden.  So create the vertex list if we need to, otherwise just 
        # update its coordinates.

        if self._face is None:
            self._face = self.batch.add(
                    num_vertices,
                    GL_TRIANGLE_STRIP,
                    self.group,
                    ('v2f', vertices),
                    ('c3B', colors),
            )
        else:
            self._face.vertices = vertices
            self._face.colors = colors
Esempio n. 17
0
    def do_draw_face(self):
        N = 48
        vertices = []

        for i in range(N + 2):
            direction = Vector.from_degrees(360 * i / N)
            radius = self._radius - (i % 2 * self.custom_face_border_width)
            vertex = self.rect.center + radius * direction
            vertices += vertex.tuple

        # Insert duplicate vertices at the beginning and end of the list,
        # otherwise this triangle strip will end up connected to any other
        # triangle strips in the scene.

        vertices = vertices[:2] + vertices + vertices[-2:]
        num_vertices = len(vertices) // 2

        color = glooey.drawing.Color.from_anything(self._color)
        colors = num_vertices * color.rgb

        # The vertex list for the face may or may not exist yet, e.g. if the
        # clock is being drawn for the first time or was previously being
        # hidden.  So create the vertex list if we need to, otherwise just
        # update its coordinates.

        if self._face is None:
            self._face = self.batch.add(
                num_vertices,
                GL_TRIANGLE_STRIP,
                self.group,
                ('v2f', vertices),
                ('c3B', colors),
            )
        else:
            self._face.vertices = vertices
            self._face.colors = colors
Esempio n. 18
0
 def on_detach_child(self, parent, child):
     self._child_position = Vector.null()
Esempio n. 19
0
 def random_velocity():
     return Vector.random(50)
Esempio n. 20
0
 def random_position():
     return field.center + Vector.random(0.4*field.height)
Esempio n. 21
0
 def set_cursor(self, image, hot_spot):
     hx, hy = Vector.from_anything(hot_spot)
     cursor = pyglet.window.ImageMouseCursor(image, hx, hy)
     self.window.set_mouse_cursor(cursor)
Esempio n. 22
0
 def on_detach_child(self, parent, child):
     self._child_position = Vector.null()
Esempio n. 23
0
 def xyw_from_xyp(self, xyp):
     return self.origin + self.heading * Vector.from_anything(xyp)
Esempio n. 24
0
 def _yield_offsets(self):
     N = len(self._children)
     for i, child in enumerate(self._children):
         offset = self.radius * Vector.from_degrees(360 * i / N)
         yield child, offset
Esempio n. 25
0
 def set_cursor(self, image, hot_spot):
     hx, hy = Vector.from_anything(hot_spot)
     cursor = pyglet.window.ImageMouseCursor(image, hx, hy)
     self.window.set_mouse_cursor(cursor)
Esempio n. 26
0
 def on_grip_press(self, x, y, button, modifiers):
     self.reference_point = Vector(x, y)
Esempio n. 27
0
 def _yield_offsets(self):
     N = len(self._children)
     for i, child in enumerate(self._children):
         offset = self.radius * Vector.from_degrees(360 * i / N)
         yield child, offset
Esempio n. 28
0
    def _update_vertex_list(self):
        if self._vertex_list is None:
            return

        texture = self._image.get_texture()

        # Get the actual texture (not just a region of a texture) associated 
        # for this image.  This will be used to make sure that 
        try:
            underlying_texture = texture.owner
        except AttributeError:
            underlying_texture = texture

        # Figure out which texture coordinates are bound to which vertices.  
        # This is not always an intuitive mapping, because textures can be 
        # rotated by changing which texture coordinates are bound to which 
        # vertices.  The in-line diagram shows which vertex is represented by 
        # each variable in the case that the image hasn't been rotated.

        a = Vector(*texture.tex_coords[0:2])     #   D┌───┐C
        b = Vector(*texture.tex_coords[3:5])     #    │   │
        c = Vector(*texture.tex_coords[6:8])     #    │   │
        d = Vector(*texture.tex_coords[9:11])    #   A└───┘B

        # Give a really nice error message if the image can't be tiled, because 
        # the restrictions on which images can be tiled don't make sense unless 
        # you really know how OpenGL works.

        error_template = """\
image can't be tiled {} because it's {} than its underlying texture ({} px vs {} px).

The most common way to get this error is to use an image that doesn't have a 
power-of-two size (e.g. 1, 2, 4, 8, etc.) in each dimension being tiled.  
OpenGL requires that textures have power-of-two dimensions, so images with 
non-power-of-two sizes end up in textures with some unused space.  This unused 
space is usually not shown, but tiling requires showing the whole texture in 
the dimension being tiled, so the unused space would ruin the effect.

Another common way to get this error is by loading the image as an `image` 
rather than a `texture`.  Pyglet tries to be smart about packing images into 
contiguous regions of memory, and sometimes this means putting images in 
textures that are larger than they need to be.  Loading the image as a texture 
avoids this logic at the expense of less well-organized memory."""

        if self._htile:
            if self._image.width != underlying_texture.width:
                raise UsageError(error_template.format('horizontally', 'narrower', self._image.width, underlying_texture.width))
            w = self._rect.width / self._image.width
        else:
            w = a.get_distance(b)

        if self._vtile:
            if self._image.height != underlying_texture.height:
                raise UsageError(error_template.format('vertically', 'shorter', self._image.height, underlying_texture.height))
            h = self._rect.height / self._image.height
        else:
            h = a.get_distance(d)

        A = a
        B = a + (b - a).get_scaled(w)
        C = a + (c - d).get_scaled(w) + (c - b).get_scaled(h)
        D = a                         + (d - a).get_scaled(h)

        self._vertex_list.tex_coords = A.tuple + B.tuple + C.tuple + D.tuple
        self._vertex_list.vertices = (
                self._rect.bottom_left.tuple +
                self._rect.bottom_right.tuple +
                self._rect.top_right.tuple +
                self._rect.top_left.tuple
        )
Esempio n. 29
0
    def _update_vertex_list(self):
        if self._vertex_list is None:
            return

        texture = self._image.get_texture()

        # Get the actual texture (not just a region of a texture) associated
        # for this image.  This will be used to make sure that
        try:
            underlying_texture = texture.owner
        except AttributeError:
            underlying_texture = texture

        # Figure out which texture coordinates are bound to which vertices.
        # This is not always an intuitive mapping, because textures can be
        # rotated by changing which texture coordinates are bound to which
        # vertices.  The in-line diagram shows which vertex is represented by
        # each variable in the case that the image hasn't been rotated.

        a = Vector(*texture.tex_coords[0:2])  #   D┌───┐C
        b = Vector(*texture.tex_coords[3:5])  #    │   │
        c = Vector(*texture.tex_coords[6:8])  #    │   │
        d = Vector(*texture.tex_coords[9:11])  #   A└───┘B

        # Give a really nice error message if the image can't be tiled, because
        # the restrictions on which images can be tiled don't make sense unless
        # you really know how OpenGL works.

        error_template = """\
image can't be tiled {} because it's {} than its underlying texture ({} px vs {} px).

The most common way to get this error is to use an image that doesn't have a 
power-of-two size (e.g. 1, 2, 4, 8, etc.) in each dimension being tiled.  
OpenGL requires that textures have power-of-two dimensions, so images with 
non-power-of-two sizes end up in textures with some unused space.  This unused 
space is usually not shown, but tiling requires showing the whole texture in 
the dimension being tiled, so the unused space would ruin the effect.

Another common way to get this error is by loading the image as an `image` 
rather than a `texture`.  Pyglet tries to be smart about packing images into 
contiguous regions of memory, and sometimes this means putting images in 
textures that are larger than they need to be.  Loading the image as a texture 
avoids this logic at the expense of less well-organized memory."""

        if self._htile:
            if self._image.width != underlying_texture.width:
                raise UsageError(
                    error_template.format('horizontally', 'narrower',
                                          self._image.width,
                                          underlying_texture.width))
            w = self._rect.width / self._image.width
        else:
            w = a.get_distance(b)

        if self._vtile:
            if self._image.height != underlying_texture.height:
                raise UsageError(
                    error_template.format('vertically', 'shorter',
                                          self._image.height,
                                          underlying_texture.height))
            h = self._rect.height / self._image.height
        else:
            h = a.get_distance(d)

        A = a
        B = a + (b - a).get_scaled(w)
        C = a + (c - d).get_scaled(w) + (c - b).get_scaled(h)
        D = a + (d - a).get_scaled(h)

        self._vertex_list.tex_coords = A.tuple + B.tuple + C.tuple + D.tuple
        self._vertex_list.vertices = (self._rect.bottom_left.tuple +
                                      self._rect.bottom_right.tuple +
                                      self._rect.top_right.tuple +
                                      self._rect.top_left.tuple)
Esempio n. 30
0
 def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
     self._pane.scroll(self.mouse_sensitivity * Vector(scroll_x, scroll_y))