Beispiel #1
0
class Tile:
    def __init__(self, sprites, svg, svgs, tile_type='tile', number=0):
        self.highlight = [svg_str_to_pixbuf(svg)]
        self.spr = Sprite(sprites, 0, 0, self.highlight[0])
        for s in svgs:
            self.highlight.append(svg_str_to_pixbuf(s))
        self.paths = []  # [[N, E, S, W], [N, E, S, W]]
        self.shape = None
        self.orientation = 0
        self.type = tile_type
        self.number = number
        self.value = 1
        self.spr.set_label_color('#FF0000')

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value

    def set_paths(self, paths):
        for c in paths:
            self.paths.append(c)

    def get_paths(self):
        return self.paths

    def reset(self):
        self.spr.set_layer(HIDE)
        self.shape = None
        self.spr.set_shape(self.highlight[0])
        while self.orientation != 0:
            self.rotate_clockwise()

    def set_shape(self, path):
        if self.shape is None:
            self.spr.set_shape(self.highlight[path + 1])
            self.shape = path
        elif self.shape != path:
            self.spr.set_shape(self.highlight[-1])

    def rotate_clockwise(self):
        """ rotate the tile and its paths """
        for i in range(len(self.paths)):
            west = self.paths[i][WEST]
            self.paths[i][WEST] = self.paths[i][SOUTH]
            self.paths[i][SOUTH] = self.paths[i][EAST]
            self.paths[i][EAST] = self.paths[i][NORTH]
            self.paths[i][NORTH] = west
        for h in range(len(self.highlight)):
            self.highlight[h] = self.highlight[h].rotate_simple(270)
        self.spr.set_shape(self.highlight[0])
        self.orientation += 90
        self.orientation %= 360

    def show_tile(self):
        self.spr.set_layer(CARDS)

    def hide(self):
        self.spr.move((-self.spr.get_dimensions()[0], 0))
Beispiel #2
0
class Card:
    # Spade   = 1,-1
    # Heart   = 2,-2
    # Club    = 3,-3
    # Diamond = 4,-4
    def __init__(self, game, c, i, x, y):
        self.north = c[0]
        self.east = c[1]
        self.south = c[2]
        self.west = c[3]
        self.orientation = 0
        self.images = []
        self.images.append(
            load_image(os.path.join(game.path, 'card%d.svg' % (i)),
                       game.card_dim * game.scale, game.card_dim * game.scale))
        for j in range(3):
            self.images.append(self.images[j].rotate_simple(90))
        # create sprite from svg file
        self.spr = Sprite(game.sprites, x, y, self.images[0])
        self.spr.set_label(i)

    def reset_image(self, game, i):
        while self.orientation != 0:
            self.rotate_ccw()

    def set_orientation(self, r, rotate_spr=True):
        while r != self.orientation:
            self.rotate_ccw(rotate_spr)

    def rotate_ccw(self, rotate_spr=True):
        # print "rotating card " + str(self.spr.label)
        tmp = self.north
        self.north = self.east
        self.east = self.south
        self.south = self.west
        self.west = tmp
        self.orientation += 90
        if self.orientation == 360:
            self.orientation = 0
        if rotate_spr is True:
            self.spr.set_shape(self.images[int(self.orientation / 90)])

    def print_card(self):
        print "(" + str(self.north) + "," + str(self.east) + \
              "," + str(self.south) + "," + str(self.west) + \
              ") " + str(self.rotate) + "ccw" + \
              " x:" + str(self.spr.x) + " y:" + str(self.spr.y)
Beispiel #3
0
class Card:
    # Spade   = 1,-1
    # Heart   = 2,-2
    # Club    = 3,-3
    # Diamond = 4,-4
    def __init__(self, game, c, i, x, y):
        self.north = c[0]
        self.east = c[1]
        self.south = c[2]
        self.west = c[3]
        self.orientation = 0
        self.images = []
        self.images.append(load_image(
            os.path.join(game.path, 'card%d.svg' % (i)),
            game.card_dim * game.scale, game.card_dim * game.scale))
        for j in range(3):
            self.images.append(self.images[j].rotate_simple(90))
        # create sprite from svg file
        self.spr = Sprite(game.sprites, x, y, self.images[0])
        self.spr.set_label(i)

    def reset_image(self, game, i):
        while self.orientation != 0:
            self.rotate_ccw()

    def set_orientation(self, r, rotate_spr=True):
        while r != self.orientation:
            self.rotate_ccw(rotate_spr)

    def rotate_ccw(self, rotate_spr=True):
        # print "rotating card " + str(self.spr.label)
        tmp = self.north
        self.north = self.east
        self.east = self.south
        self.south = self.west
        self.west = tmp
        self.orientation += 90
        if self.orientation == 360:
            self.orientation = 0
        if rotate_spr is True:
            self.spr.set_shape(self.images[int(self.orientation / 90)])

    def print_card(self):
        print "(" + str(self.north) + "," + str(self.east) + \
              "," + str(self.south) + "," + str(self.west) + \
              ") " + str(self.rotate) + "ccw" + \
              " x:" + str(self.spr.x) + " y:" + str(self.spr.y)
class Turtle:
    def __init__(self, turtles, turtle_name, turtle_colors=None):
        ''' The turtle is not a block, just a sprite with an orientation '''
        self.spr = None
        self.label_block = None
        self._turtles = turtles
        self._shapes = []
        self._custom_shapes = False
        self._name = turtle_name
        self._hidden = False
        self._remote = False
        self._x = 0.0
        self._y = 0.0
        self._heading = 0.0
        self._half_width = 0
        self._half_height = 0
        self._drag_radius = None
        self._pen_shade = 50
        self._pen_color = 0
        self._pen_gray = 100
        if self._turtles.turtle_window.coord_scale == 1:
            self._pen_size = 5
        else:
            self._pen_size = 1
        self._pen_state = True
        self._pen_fill = False
        self._poly_points = []

        self._prep_shapes(turtle_name, self._turtles, turtle_colors)

        # Create a sprite for the turtle in interactive mode.
        if turtles.sprite_list is not None:
            self.spr = Sprite(self._turtles.sprite_list, 0, 0, self._shapes[0])

            self._calculate_sizes()

            # Choose a random angle from which to attach the turtle
            # label to be used when sharing.
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            width = self._shapes[0].get_width()
            radius = width * 0.67
            # Restrict the angle to the sides: 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [
                    int(radius * sin(angle)),
                    int(radius * cos(angle) + width / 2.0)
                ]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [
                    int(radius * sin(angle) + width / 2.0),
                    int(radius * cos(angle) + width / 2.0)
                ]

        self._turtles.add_to_dict(turtle_name, self)

    def _calculate_sizes(self):
        self._half_width = int(self.spr.rect.width / 2.0)
        self._half_height = int(self.spr.rect.height / 2.0)
        self._drag_radius = ((self._half_width * self._half_width) +
                             (self._half_height * self._half_height)) / 6

    def set_remote(self):
        self._remote = True

    def get_remote(self):
        return self._remote

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = [
                '#%06x' % (COLOR_TABLE[fill]),
                '#%06x' % (COLOR_TABLE[stroke])
            ]
            self._shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self._shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self._heading, share=False)

    def set_shapes(self, shapes, i=0):
        ''' Reskin the turtle '''
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self._shapes):
                self._shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self._shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self._turtles.turtle_window.running_sugar)
            if self._heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2.0, nh / 2.0)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2.0, -nh / 2.0)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.0,
                                              (nh - h) / 2.0)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self._shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self._heading + 5) % 360 / (360 / SHAPES)
                self._shapes[j] = shapes[0]
        self._custom_shapes = True
        self.show()
        self._calculate_sizes()

    def reset_shapes(self):
        ''' Reset the shapes to the standard turtle '''
        if self._custom_shapes:
            self._shapes = generate_turtle_pixbufs(self.colors)
            self._custom_shapes = False
            self._calculate_sizes()

    def set_heading(self, heading, share=True):
        ''' Set the turtle heading (one shape per 360/SHAPES degrees) '''
        try:
            self._heading = heading
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def _update_sprite_heading(self):
        ''' Update the sprite to reflect the current heading '''
        i = (int(self._heading + 5) % 360) / (360 / SHAPES)
        if not self._hidden and self.spr is not None:
            try:
                self.spr.set_shape(self._shapes[i])
            except IndexError:
                self.spr.set_shape(self._shapes[0])

    def set_color(self, color=None, share=True):
        ''' Set the pen color for this turtle. '''
        # Special case for color blocks
        if color is not None and color in COLORDICT:
            self.set_shade(COLORDICT[color][1], share)
            self.set_gray(COLORDICT[color][2], share)
            if COLORDICT[color][0] is not None:
                self.set_color(COLORDICT[color][0], share)
                color = COLORDICT[color][0]
            else:
                color = self._pen_color
        elif color is None:
            color = self._pen_color

        try:
            self._pen_color = color
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'c|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_color)]))
            self._turtles.turtle_window.send_event(event)

    def set_gray(self, gray=None, share=True):
        ''' Set the pen gray level for this turtle. '''
        if gray is not None:
            try:
                self._pen_gray = gray
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        if self._pen_gray < 0:
            self._pen_gray = 0
        if self._pen_gray > 100:
            self._pen_gray = 100

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'g|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_gray)]))
            self._turtles.turtle_window.send_event(event)

    def set_shade(self, shade=None, share=True):
        ''' Set the pen shade for this turtle. '''
        if shade is not None:
            try:
                self._pen_shade = shade
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 's|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_shade)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_size(self, pen_size=None, share=True):
        ''' Set the pen size for this turtle. '''
        if pen_size is not None:
            try:
                self._pen_size = max(0, pen_size)
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        self._turtles.turtle_window.canvas.set_pen_size(
            self._pen_size * self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'w|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_size)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_state(self, pen_state=None, share=True):
        ''' Set the pen state (down==True) for this turtle. '''
        if pen_state is not None:
            self._pen_state = pen_state

        if self._turtles.turtle_window.sharing() and share:
            event = 'p|%s' % (data_to_string(
                [self._turtles.turtle_window.nick, self._pen_state]))
            self._turtles.turtle_window.send_event(event)

    def set_fill(self, state=False):
        self._pen_fill = state
        if not self._pen_fill:
            self._poly_points = []

    def set_poly_points(self, poly_points=None):
        if poly_points is not None:
            self._poly_points = poly_points[:]

    def start_fill(self):
        self._pen_fill = True
        self._poly_points = []

    def stop_fill(self, share=True):
        self._pen_fill = False
        if len(self._poly_points) == 0:
            return

        self._turtles.turtle_window.canvas.fill_polygon(self._poly_points)

        if self._turtles.turtle_window.sharing() and share:
            shared_poly_points = []
            for p in self._poly_points:
                x, y = self._turtles.turtle_to_screen_coordinates((p[1], p[2]))
                if p[0] in ['move', 'line']:
                    shared_poly_points.append((p[0], x, y))
                elif p[0] in ['rarc', 'larc']:
                    shared_poly_points.append((p[0], x, y, p[3], p[4], p[5]))
                event = 'F|%s' % (data_to_string(
                    [self._turtles.turtle_window.nick, shared_poly_points]))
            self._turtles.turtle_window.send_event(event)
        self._poly_points = []

    def hide(self):
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self._hidden = True

    def show(self):
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self._hidden = False
        self.move_turtle_spr((self._x, self._y))
        self.set_heading(self._heading, share=False)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move_turtle(self, pos=None):
        ''' Move the turtle's position '''
        if pos is None:
            pos = self.get_xy()

        self._x, self._y = pos[0], pos[1]
        if self.spr is not None:
            self.move_turtle_spr(pos)

    def move_turtle_spr(self, pos):
        ''' Move the turtle's sprite '''
        pos = self._turtles.turtle_to_screen_coordinates(pos)

        pos[0] -= self._half_width
        pos[1] -= self._half_height

        if not self._hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move(
                (pos[0] + self.label_xy[0], pos[1] + self.label_xy[1]))

    def right(self, degrees, share=True):
        ''' Rotate turtle clockwise '''
        try:
            self._heading += degrees
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def _draw_line(self, old, new, pendown):
        if self._pen_state and pendown:
            self._turtles.turtle_window.canvas.set_source_rgb()
            pos1 = self._turtles.turtle_to_screen_coordinates(old)
            pos2 = self._turtles.turtle_to_screen_coordinates(new)
            self._turtles.turtle_window.canvas.draw_line(
                pos1[0], pos1[1], pos2[0], pos2[1])
            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', pos1[0], pos1[1]))
                self._poly_points.append(('line', pos2[0], pos2[1]))

    def forward(self, distance, share=True):
        scaled_distance = distance * self._turtles.turtle_window.coord_scale

        old = self.get_xy()
        try:
            xcor = old[0] + scaled_distance * sin(self._heading * DEGTOR)
            ycor = old[1] + scaled_distance * cos(self._heading * DEGTOR)
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._draw_line(old, (xcor, ycor), True)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'f|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 int(distance)]))
            self._turtles.turtle_window.send_event(event)

    def set_xy(self, x, y, share=True, pendown=True, dragging=False):
        old = self.get_xy()
        try:
            if dragging:
                xcor = x
                ycor = y
            else:
                xcor = x * self._turtles.turtle_window.coord_scale
                ycor = y * self._turtles.turtle_window.coord_scale
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._draw_line(old, (xcor, ycor), pendown)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'x|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [round_int(xcor), round_int(ycor)]
            ]))
            self._turtles.turtle_window.send_event(event)

    def arc(self, a, r, share=True):
        ''' Draw an arc '''
        if self._pen_state:
            self._turtles.turtle_window.canvas.set_source_rgb()
        try:
            if a < 0:
                pos = self.larc(-a, r)
            else:
                pos = self.rarc(a, r)
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self.move_turtle(pos)

        if self._turtles.turtle_window.sharing() and share:
            event = 'a|%s' % (data_to_string([
                self._turtles.turtle_window.nick, [round_int(a),
                                                   round_int(r)]
            ]))
            self._turtles.turtle_window.send_event(event)

    def rarc(self, a, r):
        ''' draw a clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] + r * cos(self._heading * DEGTOR)
        cy = pos[1] - r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.rarc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', npos[0], npos[1]))
                    self._poly_points.append(
                        ('rarc', npos[0], npos[1], r,
                         (self._heading - 180) * DEGTOR,
                         (self._heading - 180 + a) * DEGTOR))

        self.right(a, False)
        return [
            cx - r * cos(self._heading * DEGTOR),
            cy + r * sin(self._heading * DEGTOR)
        ]

    def larc(self, a, r):
        ''' draw a counter-clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] - r * cos(self._heading * DEGTOR)
        cy = pos[1] + r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.larc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', npos[0], npos[1]))
                    self._poly_points.append(
                        ('larc', npos[0], npos[1], r, (self._heading) * DEGTOR,
                         (self._heading - a) * DEGTOR))

        self.right(-a, False)
        return [
            cx + r * cos(self._heading * DEGTOR),
            cy - r * sin(self._heading * DEGTOR)
        ]

    def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
        ''' Draw a pixbuf '''

        self._turtles.turtle_window.canvas.draw_pixbuf(pixbuf, a, b, x, y, w,
                                                       h, self._heading)

        if self._turtles.turtle_window.sharing() and share:
            if self._turtles.turtle_window.running_sugar:
                tmp_path = get_path(self._turtles.turtle_window.activity,
                                    'instance')
            else:
                tmp_path = '/tmp'
            tmp_file = os.path.join(
                get_path(self._turtles.turtle_window.activity, 'instance'),
                'tmpfile.png')
            pixbuf.save(tmp_file, 'png', {'quality': '100'})
            data = image_to_base64(tmp_file, tmp_path)
            height = pixbuf.get_height()
            width = pixbuf.get_width()

            pos = self._turtles.screen_to_turtle_coordinates((x, y))

            event = 'P|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [
                    round_int(a),
                    round_int(b),
                    round_int(pos[0]),
                    round_int(pos[1]),
                    round_int(w),
                    round_int(h),
                    round_int(width),
                    round_int(height), data
                ]
            ]))
            gobject.idle_add(self._turtles.turtle_window.send_event, event)

            os.remove(tmp_file)

    def draw_text(self, label, x, y, size, w, share=True):
        ''' Draw text '''
        self._turtles.turtle_window.canvas.draw_text(
            label, x, y, size, w, self._heading,
            self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'W|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [
                    label,
                    round_int(x),
                    round_int(y),
                    round_int(size),
                    round_int(w)
                ]
            ]))
            self._turtles.turtle_window.send_event(event)

    def get_name(self):
        return self._name

    def get_xy(self):
        return [self._x, self._y]

    def get_x(self):
        return self._x

    def get_y(self):
        return self._y

    def get_heading(self):
        return self._heading

    def get_color(self):
        return self._pen_color

    def get_gray(self):
        return self._pen_gray

    def get_shade(self):
        return self._pen_shade

    def get_pen_size(self):
        return self._pen_size

    def get_pen_state(self):
        return self._pen_state

    def get_fill(self):
        return self._pen_fill

    def get_poly_points(self):
        return self._poly_points

    def get_pixel(self):
        pos = self._turtles.turtle_to_screen_coordinates(self.get_xy())
        return self._turtles.turtle_window.canvas.get_pixel(pos[0], pos[1])

    def get_drag_radius(self):
        if self._drag_radius is None:
            self._calculate_sizes()
        return self._drag_radius
class Turtle:

    def __init__(self, turtles, key, turtle_colors=None):
        """ The turtle is not a block, just a sprite with an orientation """
        self.x = 0
        self.y = 0
        self.hidden = False
        self.shapes = []
        self.custom_shapes = False
        self.type = 'turtle'
        self.name = key
        self.heading = 0
        self.pen_shade = 50
        self.pen_color = 0
        self.pen_gray = 100
        self.pen_size = 5
        self.pen_state = True
        self.label_block = None

        self._prep_shapes(key, turtles, turtle_colors)

        # Choose a random angle from which to attach the turtle label
        if turtles.sprite_list is not None:
            self.spr = Sprite(turtles.sprite_list, 0, 0, self.shapes[0])
            angle = uniform(0, pi * 4 / 3.0) # 240 degrees
            w = self.shapes[0].get_width()
            r = w * 0.67
            # Restrict angle the the sides 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [int(r * sin(angle)),
                                 int(r * cos(angle) + w / 2.0)]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [int(r * sin(angle) + w / 2.0),
                                 int(r * cos(angle) + w / 2.0)]
        else:
            self.spr = None
        turtles.add_to_dict(key, self)

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (COLOR_TABLE[fill]),
                           '#%06x' % (COLOR_TABLE[stroke])]
            self.shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self.shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self.heading)

    def set_shapes(self, shapes, i=0):
        """ Reskin the turtle """
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self.shapes):
                self.shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self.shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self.tw.running_sugar)
            if self.heading == 0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2., nh / 2.)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2., -nh / 2.)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.,
                                              (nh - h) / 2.)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self.shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self.heading + 5) % 360 / (360 / SHAPES)
                self.shapes[j] = shapes[0]
        self.custom_shapes = True
        self.show()

    def reset_shapes(self):
        """ Reset the shapes to the standard turtle """
        if self.custom_shapes:
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.custom_shapes = False

    def set_heading(self, heading):
        """ Set the turtle heading (one shape per 360/SHAPES degrees) """
        self.heading = heading
        i = (int(self.heading + 5) % 360) / (360 / SHAPES)
        if not self.hidden and self.spr is not None:
            try:
                self.spr.set_shape(self.shapes[i])
            except IndexError:
                self.spr.set_shape(self.shapes[0])

    def set_color(self, color):
        """ Set the pen color for this turtle. """
        self.pen_color = color

    def set_gray(self, gray):
        """ Set the pen gray level for this turtle. """
        self.pen_gray = gray

    def set_shade(self, shade):
        """ Set the pen shade for this turtle. """
        self.pen_shade = shade

    def set_pen_size(self, pen_size):
        """ Set the pen size for this turtle. """
        self.pen_size = pen_size

    def set_pen_state(self, pen_state):
        """ Set the pen state (down==True) for this turtle. """
        self.pen_state = pen_state

    def hide(self):
        """ Hide the turtle. """
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self.hidden = True

    def show(self):
        """ Show the turtle. """
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self.hidden = False
        self.move((self.x, self.y))
        self.set_heading(self.heading)
        if self.label_block is not None:
            self.label_block.spr.move((self.x + self.label_xy[0],
                                       self.y + self.label_xy[1]))
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move(self, pos):
        """ Move the turtle. """
        self.x, self.y = int(pos[0]), int(pos[1])
        if not self.hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move((pos[0] + self.label_xy[0],
                                       pos[1] + self.label_xy[1]))
        return(self.x, self.y)

    def get_name(self):
        ''' return turtle name (key) '''
        return self.name

    def get_xy(self):
        """ Return the turtle's x, y coordinates. """
        return(self.x, self.y)

    def get_heading(self):
        """ Return the turtle's heading. """
        return(self.heading)

    def get_color(self):
        """ Return the turtle's color. """
        return(self.pen_color)

    def get_gray(self):
        """ Return the turtle's gray level. """
        return(self.pen_gray)

    def get_shade(self):
        """ Return the turtle's shade. """
        return(self.pen_shade)

    def get_pen_size(self):
        """ Return the turtle's pen size. """
        return(self.pen_size)

    def get_pen_state(self):
        """ Return the turtle's pen state. """
        return(self.pen_state)
Beispiel #6
0
class Tile:

    def __init__(self, sprites, svg, svgs, tile_type='tile', number=0):
        self.highlight = [svg_str_to_pixbuf(svg)]
        self.spr = Sprite(sprites, 0, 0, self.highlight[0])
        for s in svgs:
            self.highlight.append(svg_str_to_pixbuf(s))
        self.paths = []  # [[N, E, S, W], [N, E, S, W]]
        self.shape = None
        self.orientation = 0
        self.type = tile_type
        self.number = number
        self.value = 1
        self.spr.set_label_color('#FF0000')

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value

    def set_paths(self, paths):
        for c in paths:
            self.paths.append(c)

    def get_paths(self):
        return self.paths

    def reset(self):
        self.spr.set_layer(HIDE)
        self.shape = None
        self.spr.set_shape(self.highlight[0])
        while self.orientation != 0:
            self.rotate_clockwise()

    def set_shape(self, path):
        if self.shape is None:
            self.spr.set_shape(self.highlight[path + 1])
            self.shape = path
        elif self.shape != path:
            self.spr.set_shape(self.highlight[-1])

    def rotate_clockwise(self):
        """ rotate the tile and its paths """
        for i in range(len(self.paths)):
            west = self.paths[i][WEST]
            self.paths[i][WEST] = self.paths[i][SOUTH]
            self.paths[i][SOUTH] = self.paths[i][EAST]
            self.paths[i][EAST] = self.paths[i][NORTH]
            self.paths[i][NORTH] = west
        for h in range(len(self.highlight)):
            self.highlight[h] = self.highlight[h].rotate_simple(270)
        self.spr.set_shape(self.highlight[0])
        self.orientation += 90
        self.orientation %= 360

    def show_tile(self):
        self.spr.set_layer(CARDS)

    def hide(self):
        self.spr.move((-self.spr.get_dimensions()[0], 0))
Beispiel #7
0
class Turtle:

    def __init__(self, turtles, turtle_name, turtle_colors=None):
        #print 'class Turtle taturtle.py: def __init__'
        ''' The turtle is not a block, just a sprite with an orientation '''
        self.spr = None
        self.label_block = None
        self._turtles = turtles
        self._shapes = []
        self._custom_shapes = False
        self._name = turtle_name
        self._hidden = False
        self._remote = False
        self._x = 0.0
        self._y = 0.0
        self._3Dz = 0.0
        self._3Dx = 0.0
        self._3Dy = 0.0
        self._heading = 0.0
        self._roll = 0.0
        self._pitch = 0.0
        self._direction = [0.0, 1.0, 0.0]
        self._points = [[0., 0., 0.]]
        self._points_penstate = [1]
        self._half_width = 0
        self._half_height = 0
        self._drag_radius = None
        self._pen_shade = 50
        self._pen_color = 0
        self._pen_gray = 100
        if self._turtles.turtle_window.coord_scale == 1:
            self._pen_size = 5
        else:
            self._pen_size = 1
        self._pen_state = True
        self._pen_fill = False
        self._poly_points = []

        self._prep_shapes(turtle_name, self._turtles, turtle_colors)

        # Create a sprite for the turtle in interactive mode.
        if turtles.sprite_list is not None:
            self.spr = Sprite(self._turtles.sprite_list, 0, 0, self._shapes[0])

            self._calculate_sizes()

            # Choose a random angle from which to attach the turtle
            # label to be used when sharing.
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            width = self._shapes[0].get_width()
            radius = width * 0.67
            # Restrict the angle to the sides: 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [int(radius * sin(angle)),
                                 int(radius * cos(angle) + width / 2.0)]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [int(radius * sin(angle) + width / 2.0),
                                 int(radius * cos(angle) + width / 2.0)]

        self._turtles.add_to_dict(turtle_name, self)

    def _calculate_sizes(self):
        #print 'taturtle.py: def _calculate_sizes'
        self._half_width = int(self.spr.rect.width / 2.0)
        self._half_height = int(self.spr.rect.height / 2.0)
        self._drag_radius = ((self._half_width * self._half_width) +
                            (self._half_height * self._half_height)) / 6

    def set_remote(self):
        #print 'taturtle.py: def set_remote'
        self._remote = True

    def get_remote(self):
        #print 'taturtle.py: def get_remote'
        return self._remote

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        #print 'taturtle.py: def _prep_shapes'
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (COLOR_TABLE[fill]),
                           '#%06x' % (COLOR_TABLE[stroke])]
            self._shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self._shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        #print 'taturtle.py: def set_turtle_colors'
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self._heading, share=False)

    def set_shapes(self, shapes, i=0):
        #print 'taturtle.py: def set_shapes'
        ''' Reskin the turtle '''
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self._shapes):
                self._shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self._shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self._turtles.turtle_window.running_sugar)
            if self._heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2.0, nh / 2.0)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2.0, -nh / 2.0)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.0,
                                              (nh - h) / 2.0)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self._shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self._heading + 5) % 360 / (360 / SHAPES)
                self._shapes[j] = shapes[0]
        self._custom_shapes = True
        self.show()
        self._calculate_sizes()

    def reset_shapes(self):
        #print 'taturtle.py: def reset_shapes'
        ''' Reset the shapes to the standard turtle '''
        if self._custom_shapes:
            self._shapes = generate_turtle_pixbufs(self.colors)
            self._custom_shapes = False
            self._calculate_sizes()

    def _apply_rotations(self):
        
	self._direction = [0., 1., 0.]
	angle = self._heading * DEGTOR * -1.0
        temp = []
        temp.append((self._direction[0] * cos(angle)) - (self._direction[1] * sin(angle)))
        temp.append((self._direction[0] * sin(angle)) + (self._direction[1] * cos(angle)))
        temp.append(self._direction[2] * 1.0)
        self._direction = temp[:]

	angle = self._roll * DEGTOR * -1.0
        temp = []
        temp.append(self._direction[0] * 1.0)
        temp.append((self._direction[1] * cos(angle)) - (self._direction[2] * sin(angle)))
        temp.append((self._direction[1] * sin(angle)) + (self._direction[2] * cos(angle)))
        self._direction = temp[:]

	angle = self._pitch * DEGTOR * -1.0
        temp = []
        temp.append((self._direction[0] * cos(angle)) + (self._direction[2] * sin(angle)))
        temp.append(self._direction[1] * 1.0)
        temp.append((self._direction[0] * -1.0 * sin(angle)) + (self._direction[2] * cos(angle)))
        self._direction = temp[:]

    def set_heading(self, heading, share=True):
        #print 'taturtle.py: def set_heading'
        ''' Set the turtle heading (one shape per 360/SHAPES degrees) ''' 

        self._heading = heading
        self._heading %= 360
 
        self._apply_rotations()

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)
    
    def set_roll(self, roll):
        ''' Set the turtle roll '''

        self._roll = roll
        self._roll %= 360

        self._apply_rotations()

    def set_pitch(self, pitch):
        ''' Set the turtle pitch '''

        self._pitch = pitch
        self._pitch %= 360
 
        self._apply_rotations()

    def _update_sprite_heading(self):

        #print 'taturtle.py: def _update_sprite_heading'
        ''' Update the sprite to reflect the current heading '''
        i = (int(self._heading + 5) % 360) / (360 / SHAPES)
        if not self._hidden and self.spr is not None:
            try:
                self.spr.set_shape(self._shapes[i])
            except IndexError:
                self.spr.set_shape(self._shapes[0])

    def set_color(self, color=None, share=True):
        #print 'taturtle.py: def set_color'
        ''' Set the pen color for this turtle. '''
        if isinstance(color, ColorObj):
            # See comment in tatype.py TYPE_BOX -> TYPE_COLOR
            color = color.color
        if color is None:
            color = self._pen_color
        # Special case for color blocks from CONSTANTS
        elif isinstance(color, Color):
            self.set_shade(color.shade, share)
            self.set_gray(color.gray, share)
            if color.color is not None:
                color = color.color
            else:
                color = self._pen_color

        self._pen_color = color

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'c|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_color)]))
            self._turtles.turtle_window.send_event(event)

    def set_gray(self, gray=None, share=True):
        #print 'taturtle.py: def set_gray'
        ''' Set the pen gray level for this turtle. '''
        if gray is not None:
            self._pen_gray = gray

        if self._pen_gray < 0:
            self._pen_gray = 0
        if self._pen_gray > 100:
            self._pen_gray = 100

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'g|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_gray)]))
            self._turtles.turtle_window.send_event(event)

    def set_shade(self, shade=None, share=True):
        #print 'taturtle.py: def set_shade'
        ''' Set the pen shade for this turtle. '''
        if shade is not None:
            self._pen_shade = shade

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 's|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_shade)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_size(self, pen_size=None, share=True):
        #print 'taturtle.py: def set_pen_size'
        ''' Set the pen size for this turtle. '''
        if pen_size is not None:
            self._pen_size = max(0, pen_size)

        self._turtles.turtle_window.canvas.set_pen_size(
            self._pen_size * self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'w|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_size)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_state(self, pen_state=None, share=True):
        #print 'taturtle.py: def set_pen_state'
        ''' Set the pen state (down==True) for this turtle. '''
        if pen_state is not None:
            self._pen_state = pen_state

        if self._turtles.turtle_window.sharing() and share:
            event = 'p|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              self._pen_state]))
            self._turtles.turtle_window.send_event(event)

    def set_fill(self, state=False):
        #print 'taturtle.py: def set_fill'
        self._pen_fill = state
        if not self._pen_fill:
            self._poly_points = []

    def set_poly_points(self, poly_points=None):
        #print 'taturtle.py: def set_poly_points'
        if poly_points is not None:
            self._poly_points = poly_points[:]

    def start_fill(self):
        #print 'taturtle.py: def start_fill'
        self._pen_fill = True
        self._poly_points = []

    def stop_fill(self, share=True):
        #print 'taturtle.py: def stop_fill'
        self._pen_fill = False
        if len(self._poly_points) == 0:
            return

        self._turtles.turtle_window.canvas.fill_polygon(self._poly_points)

        if self._turtles.turtle_window.sharing() and share:
            shared_poly_points = []
            for p in self._poly_points:
                x, y = self._turtles.turtle_to_screen_coordinates(
                    (p[1], p[2]))
                if p[0] in ['move', 'line']:
                    shared_poly_points.append((p[0], x, y))
                elif p[0] in ['rarc', 'larc']:
                    shared_poly_points.append((p[0], x, y, p[3], p[4], p[5]))
                event = 'F|%s' % (data_to_string(
                        [self._turtles.turtle_window.nick,
                         shared_poly_points]))
            self._turtles.turtle_window.send_event(event)
        self._poly_points = []

    def hide(self):
        #print 'taturtle.py: def hide'
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self._hidden = True

    def show(self):
        #print 'taturtle.py: def show'
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self._hidden = False
        self.move_turtle_spr((self._x, self._y))
        self.set_heading(self._heading, share=False)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move_turtle(self, pos=None):
        #print 'taturtle.py: def move_turtle'
        ''' Move the turtle's position '''
        if pos is None:
            pos = self.get_xy()

        self._x, self._y = pos[0], pos[1]
        if self.spr is not None:
            self.move_turtle_spr(pos)

    def move_turtle_spr(self, pos):
        #print 'taturtle.py: def move_turtle_spr'
        ''' Move the turtle's sprite '''
        pos = self._turtles.turtle_to_screen_coordinates(pos)

        pos[0] -= self._half_width
        pos[1] -= self._half_height

        if not self._hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move((pos[0] + self.label_xy[0],
                                       pos[1] + self.label_xy[1]))
    def reset_3D(self):
        self._3Dx, self._3Dy, self._3Dz = 0.0, 0.0, 0.0
        self._direction = [0.0, 1.0, 0.0]
        self._roll, self._pitch = 0.0, 0.0
        self._points = [[0., 0., 0.]]
        self._points_penstate = [1]

    def right(self, degrees, share=True):
        #print 'taturtle.py: def right'
        ''' Rotate turtle clockwise '''
        self._heading += degrees
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def left(self, degrees, share=True):
        #print 'taturtle.py: def left'
        degrees = 0 - degrees
        self.right(degrees, share)

    def _draw_line(self, old, new, pendown):
        #print 'taturtle.py: def _draw_line'
        if self._pen_state and pendown:
            self._turtles.turtle_window.canvas.set_source_rgb()
            pos1 = self._turtles.turtle_to_screen_coordinates(old)
            pos2 = self._turtles.turtle_to_screen_coordinates(new)
            self._turtles.turtle_window.canvas.draw_line(pos1[0], pos1[1],
                                                         pos2[0], pos2[1])
            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', pos1[0], pos1[1]))
                self._poly_points.append(('line', pos2[0], pos2[1]))

    def draw_obj(self, file_name):

        vertices = []
        lines = []
        file_handle = open(file_name, 'r')

        for line in file_handle:
            temp = line.split()
            if temp[0] == 'v':
                vertices.append([float(temp[1]), float(temp[2]), float(temp[3])])
            if temp[0] == 'l':
                lines.append([int(temp[1]), int(temp[2])])

        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height

        for line in lines:
            source = vertices[line[0] - 1]
            dest = vertices[line[1] - 1]
            
            source_point = Point3D(source[0], source[1], source[2])
            p1 = source_point.project(width, height, 512, 512)
            pair1 = [p1.x, p1.y]
            pos1 = self._turtles.screen_to_turtle_coordinates(pair1)

            dest_point = Point3D(dest[0], dest[1], dest[2])
            p2 = dest_point.project(width, height, 512, 512)
            pair2 = [p2.x, p2.y]
            pos2 = self._turtles.screen_to_turtle_coordinates(pair2)

            self._draw_line(pos1, pos2, True)
            self.move_turtle((pos2[0], pos2[1]))

        return vertices, lines

    def forward(self, distance, share=True):
        #print 'taturtle.py: def forward'
        scaled_distance = distance * self._turtles.turtle_window.coord_scale

        old = self.get_xy() #Projected Point
        old_3D = self.get_3Dpoint() #Actual Point

        #xcor = old[0] + scaled_distance * sin(self._heading * DEGTOR)
        #ycor = old[1] + scaled_distance * cos(self._heading * DEGTOR)

        xcor = old_3D[0] + scaled_distance * self._direction[0]
        ycor = old_3D[1] + scaled_distance * self._direction[1]
        zcor = old_3D[2] + scaled_distance * self._direction[2]

        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height
        
        old_point = Point3D(old_3D[0], old_3D[1], old_3D[2]) # Old point as Point3D object
        p = old_point.project(width, height, 512, 512) # Projected Old Point
        new_x, new_y = p.x, p.y
        pair1 = [new_x, new_y]
        pos1 = self._turtles.screen_to_turtle_coordinates(pair1)
        
        '''
        for i, val in enumerate(old_3D):
            if (abs(val) < 0.0001):
                old_3D[i] = 0.
            old_3D[i] = round(old_3D[i], 2)
        self._points.append([old_3D[0], old_3D[1], old_3D[2]])
        if (self._pen_state):
            self._points_penstate.append(1)
        else:
            self._points_penstate.append(0)
        '''

        self._3Dx, self._3Dy, self._3Dz = xcor, ycor, zcor
        self.store_data()

        new_point = Point3D(xcor, ycor, zcor) # New point as 3D object
        p = new_point.project(width, height, 512, 512) # Projected New Point
        new_x, new_y = p.x, p.y
        pair2 = [new_x, new_y]
        pos2 = self._turtles.screen_to_turtle_coordinates(pair2)
        #print 'new = ', new_point.x, new_point.y, new_point.z

        self._draw_line(pos1, pos2, True)
        #self.move_turtle((xcor, ycor))
        self.move_turtle((pos2[0], pos2[1]))

        if self._turtles.turtle_window.sharing() and share:
            event = 'f|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              int(distance)]))
            self._turtles.turtle_window.send_event(event)

    def backward(self, distance, share=True):
        #print 'taturtle.py: def backward'
        distance = 0 - distance
        self.forward(distance, share)

    def set_xy(self, x, y, share=True, pendown=True, dragging=False):
        #print 'taturtle.py: def set_xy'
        old = self.get_xy()
        if dragging:
            xcor = x
            ycor = y
        else:
            xcor = x * self._turtles.turtle_window.coord_scale
            ycor = y * self._turtles.turtle_window.coord_scale

        self._draw_line(old, (xcor, ycor), pendown)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'x|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(xcor),
                                               round_int(ycor)]]))
            self._turtles.turtle_window.send_event(event)

    def set_xyz(self, x, y, z):
        ''' Set the x, y and z coordinates '''

        self._3Dx, self._3Dy, self._3Dz = x, y, z
        self.store_data()
        point_3D = Point3D(x, y, z)
        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height
        p = point_3D.project(width, height, 512, 512)
        new_x, new_y = p.x, p.y
        pair = [new_x, new_y]
        pos = self._turtles.screen_to_turtle_coordinates(pair)
        self.set_xy(pos[0], pos[1])

    def store_data(self):

        if(abs(self._3Dx) < 0.0001):
            self._3Dx = 0.
        if(abs(self._3Dy) < 0.0001):
            self._3Dy = 0.
        if(abs(self._3Dz) < 0.0001):
            self._3Dz = 0.
        self._3Dx = round(self._3Dx, 2)
        self._3Dy = round(self._3Dy, 2)
        self._3Dz = round(self._3Dz, 2)

        self._points.append([self._3Dx, self._3Dy, self._3Dz])
        if (self._pen_state):
            self._points_penstate.append(1)
        else:
            self._points_penstate.append(0)
    def arc(self, a, r, share=True):
        #print 'taturtle.py: def arc'
        ''' Draw an arc '''
        if self._pen_state:
            self._turtles.turtle_window.canvas.set_source_rgb()
        if a < 0:
            pos = self.larc(-a, r)
        else:
            pos = self.rarc(a, r)

        self.move_turtle(pos)

        if self._turtles.turtle_window.sharing() and share:
            event = 'a|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(a), round_int(r)]]))
            self._turtles.turtle_window.send_event(event)

    def rarc(self, a, r):
        #print 'taturtle.py: def rarc'
        ''' draw a clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] + r * cos(self._heading * DEGTOR)
        cy = pos[1] - r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.rarc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                self._poly_points.append(('move', npos[0], npos[1]))
                self._poly_points.append(('rarc', npos[0], npos[1], r,
                                          (self._heading - 180) * DEGTOR,
                                          (self._heading - 180 + a) * DEGTOR))

        self.right(a, False)
        return [cx - r * cos(self._heading * DEGTOR),
                cy + r * sin(self._heading * DEGTOR)]

    def larc(self, a, r):
        #print 'taturtle.py: def larc'
        ''' draw a counter-clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] - r * cos(self._heading * DEGTOR)
        cy = pos[1] + r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.larc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                self._poly_points.append(('move', npos[0], npos[1]))
                self._poly_points.append(('larc', npos[0], npos[1], r,
                                          (self._heading) * DEGTOR,
                                          (self._heading - a) * DEGTOR))

        self.right(-a, False)
        return [cx + r * cos(self._heading * DEGTOR),
                cy - r * sin(self._heading * DEGTOR)]

    def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
        #print 'taturtle.py: def draw_pixbuf'
        ''' Draw a pixbuf '''
        self._turtles.turtle_window.canvas.draw_pixbuf(
            pixbuf, a, b, x, y, w, h, self._heading)

        if self._turtles.turtle_window.sharing() and share:
            if self._turtles.turtle_window.running_sugar:
                tmp_path = get_path(self._turtles.turtle_window.activity,
                                    'instance')
            else:
                tmp_path = '/tmp'
            tmp_file = os.path.join(
                get_path(self._turtles.turtle_window.activity, 'instance'),
                'tmpfile.png')
            pixbuf.save(tmp_file, 'png', {'quality': '100'})
            data = image_to_base64(tmp_file, tmp_path)
            height = pixbuf.get_height()
            width = pixbuf.get_width()

            pos = self._turtles.screen_to_turtle_coordinates((x, y))

            event = 'P|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(a), round_int(b),
                                               round_int(pos[0]),
                                               round_int(pos[1]),
                                               round_int(w), round_int(h),
                                               round_int(width),
                                               round_int(height),
                                               data]]))
            gobject.idle_add(self._turtles.turtle_window.send_event, event)

            os.remove(tmp_file)

    def draw_text(self, label, x, y, size, w, share=True):
        #print 'taturtle.py: def draw_text'
        ''' Draw text '''
        self._turtles.turtle_window.canvas.draw_text(
            label, x, y, size, w, self._heading,
            self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'W|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [label, round_int(x),
                                               round_int(y), round_int(size),
                                               round_int(w)]]))
            self._turtles.turtle_window.send_event(event)

    def read_pixel(self):
        #print 'taturtle.py: def read_pixel'
        """ Read r, g, b, a from the canvas and push b, g, r to the stack """
        r, g, b, a = self.get_pixel()
        self._turtles.turtle_window.lc.heap.append(b)
        self._turtles.turtle_window.lc.heap.append(g)
        self._turtles.turtle_window.lc.heap.append(r)

    def get_color_index(self):
        #print 'taturtle.py: def get_color_index'
        r, g, b, a = self.get_pixel()
        color_index = self._turtles.turtle_window.canvas.get_color_index(
            r, g, b)
        return color_index

    def get_name(self):
        #print 'taturtle.py: def get_name'
        return self._name

    def get_xy(self):
        #print 'taturtle.py: def get_xy'
        return [self._x, self._y]
    
    def get_3Dpoint(self):
        return [self._3Dx, self._3Dy, self._3Dz]
    
    def get_x(self):
        #print 'taturtle.py: def get_x'
        return self._3Dx

    def get_y(self):
        #print 'taturtle.py: def get_y'
        return self._3Dy

    def get_z(self):
        return self._3Dz

    def get_heading(self):
        #print 'taturtle.py: def get_heading'
        return self._heading
    
    def get_roll(self):
        return self._roll

    def get_pitch(self):
        return self._pitch

    def get_color(self):
        #print 'taturtle.py: def get_color'
        return self._pen_color

    def get_gray(self):
        #print 'taturtle.py: def get_gray'
        return self._pen_gray

    def get_shade(self):
        #print 'taturtle.py: def get_shade'
        return self._pen_shade

    def get_pen_size(self):
        #print 'taturtle.py: def get_pen_size'
        return self._pen_size

    def get_pen_state(self):
        #print 'taturtle.py: def get_pen_state'
        return self._pen_state

    def get_fill(self):
        #print 'taturtle.py: def get_fill'
        return self._pen_fill

    def get_poly_points(self):
        #print 'taturtle.py: def get_poly_points'
        return self._poly_points

    def get_pixel(self):
        #print 'taturtle.py: def get_pixel'
        pos = self._turtles.turtle_to_screen_coordinates(self.get_xy())
        return self._turtles.turtle_window.canvas.get_pixel(pos[0], pos[1])

    def get_drag_radius(self):
        #print 'taturtle.py: def get_drag_radius'
        if self._drag_radius is None:
            self._calculate_sizes()
        return self._drag_radius
Beispiel #8
0
class Selector():

    ''' Selector class abstraction  '''

    def __init__(self, turtle_window, n):
        '''This class handles the display of palette selectors (Only relevant
        to GNOME version and very old versions of Sugar).
        '''

        self.shapes = []
        self.spr = None
        self._turtle_window = turtle_window
        self._index = n

        if not n < len(palette_names):
            # Shouldn't happen, but hey...
            debug_output('palette index %d is out of range' % n,
                         self._turtle_window.running_sugar)
            self._name = 'extras'
        else:
            self._name = palette_names[n]

        icon_pathname = None
        for path in self._turtle_window.icon_paths:
            if os.path.exists(os.path.join(path, '%soff.svg' % (self._name))):
                icon_pathname = os.path.join(path, '%soff.svg' % (self._name))
                break

        if icon_pathname is not None:
            off_shape = svg_str_to_pixbuf(svg_from_file(icon_pathname))
        else:
            off_shape = svg_str_to_pixbuf(svg_from_file(os.path.join(
                self._turtle_window.icon_paths[0], 'extrasoff.svg')))
            error_output('Unable to open %soff.svg' % (self._name),
                         self._turtle_window.running_sugar)

        icon_pathname = None
        for path in self._turtle_window.icon_paths:
            if os.path.exists(os.path.join(path, '%son.svg' % (self._name))):
                icon_pathname = os.path.join(path, '%son.svg' % (self._name))
                break

        if icon_pathname is not None:
            on_shape = svg_str_to_pixbuf(svg_from_file(icon_pathname))
        else:
            on_shape = svg_str_to_pixbuf(svg_from_file(os.path.join(
                self._turtle_window.icon_paths[0], 'extrason.svg')))
            error_output('Unable to open %son.svg' % (self._name),
                         self._turtle_window.running_sugar)

        self.shapes.append(off_shape)
        self.shapes.append(on_shape)

        x = int(ICON_SIZE * self._index)
        self.spr = Sprite(self._turtle_window.sprite_list, x, 0, off_shape)
        self.spr.type = 'selector'
        self.spr.name = self._name
        self.set_layer()

    def set_shape(self, i):
        if self.spr is not None and i in [0, 1]:
            self.spr.set_shape(self.shapes[i])

    def set_layer(self, layer=TAB_LAYER):
        if self.spr is not None:
            self.spr.set_layer(layer)

    def hide(self):
        if self.spr is not None:
            self.spr.hide()
class Turtle:

    def __init__(self, turtles, turtle_name, turtle_colors=None):
        ''' The turtle is not a block, just a sprite with an orientation '''
        self.spr = None
        self.label_block = None
        self._turtles = turtles
        self._shapes = []
        self._custom_shapes = False
        self._name = turtle_name
        self._hidden = False
        self._remote = False
        self._x = 0.0
        self._y = 0.0
        self._heading = 0.0
        self._half_width = 0
        self._half_height = 0
        self._drag_radius = None
        self._pen_shade = 50
        self._pen_color = 0
        self._pen_gray = 100
        if self._turtles.turtle_window.coord_scale == 1:
            self._pen_size = 5
        else:
            self._pen_size = 1
        self._pen_state = True
        self._pen_fill = False
        self._poly_points = []

        self._prep_shapes(turtle_name, self._turtles, turtle_colors)

        # Create a sprite for the turtle in interactive mode.
        if turtles.sprite_list is not None:
            self.spr = Sprite(self._turtles.sprite_list, 0, 0, self._shapes[0])

            self._calculate_sizes()

            # Choose a random angle from which to attach the turtle
            # label to be used when sharing.
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            width = self._shapes[0].get_width()
            radius = width * 0.67
            # Restrict the angle to the sides: 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [int(radius * sin(angle)),
                                 int(radius * cos(angle) + width / 2.0)]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [int(radius * sin(angle) + width / 2.0),
                                 int(radius * cos(angle) + width / 2.0)]

        self._turtles.add_to_dict(turtle_name, self)

    def _calculate_sizes(self):
        self._half_width = int(self.spr.rect.width / 2.0)
        self._half_height = int(self.spr.rect.height / 2.0)
        self._drag_radius = ((self._half_width * self._half_width) +
                            (self._half_height * self._half_height)) / 6

    def set_remote(self):
        self._remote = True

    def get_remote(self):
        return self._remote

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (COLOR_TABLE[fill]),
                           '#%06x' % (COLOR_TABLE[stroke])]
            self._shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self._shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self._heading, share=False)

    def set_shapes(self, shapes, i=0):
        ''' Reskin the turtle '''
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self._shapes):
                self._shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self._shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self._turtles.turtle_window.running_sugar)
            if self._heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2.0, nh / 2.0)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2.0, -nh / 2.0)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.0,
                                              (nh - h) / 2.0)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self._shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self._heading + 5) % 360 / (360 / SHAPES)
                self._shapes[j] = shapes[0]
        self._custom_shapes = True
        self.show()
        self._calculate_sizes()

    def reset_shapes(self):
        ''' Reset the shapes to the standard turtle '''
        if self._custom_shapes:
            self._shapes = generate_turtle_pixbufs(self.colors)
            self._custom_shapes = False
            self._calculate_sizes()

    def set_heading(self, heading, share=True):
        ''' Set the turtle heading (one shape per 360/SHAPES degrees) '''
        try:
            self._heading = heading
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def _update_sprite_heading(self):
        ''' Update the sprite to reflect the current heading '''
        i = (int(self._heading + 5) % 360) / (360 / SHAPES)
        if not self._hidden and self.spr is not None:
            try:
                self.spr.set_shape(self._shapes[i])
            except IndexError:
                self.spr.set_shape(self._shapes[0])

    def set_color(self, color=None, share=True):
        ''' Set the pen color for this turtle. '''
        # Special case for color blocks
        if color is not None and color in COLORDICT:
            self.set_shade(COLORDICT[color][1], share)
            self.set_gray(COLORDICT[color][2], share)
            if COLORDICT[color][0] is not None:
                self.set_color(COLORDICT[color][0], share)
                color = COLORDICT[color][0]
            else:
                color = self._pen_color
        elif color is None:
            color = self._pen_color

        try:
            self._pen_color = color
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'c|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_color)]))
            self._turtles.turtle_window.send_event(event)

    def set_gray(self, gray=None, share=True):
        ''' Set the pen gray level for this turtle. '''
        if gray is not None:
            try:
                self._pen_gray = gray
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        if self._pen_gray < 0:
            self._pen_gray = 0
        if self._pen_gray > 100:
            self._pen_gray = 100

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'g|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_gray)]))
            self._turtles.turtle_window.send_event(event)

    def set_shade(self, shade=None, share=True):
        ''' Set the pen shade for this turtle. '''
        if shade is not None:
            try:
                self._pen_shade = shade
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 's|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_shade)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_size(self, pen_size=None, share=True):
        ''' Set the pen size for this turtle. '''
        if pen_size is not None:
            try:
                self._pen_size = max(0, pen_size)
            except (TypeError, ValueError):
                debug_output('bad value sent to %s' % (__name__),
                             self._turtles.turtle_window.running_sugar)
                return

        self._turtles.turtle_window.canvas.set_pen_size(
            self._pen_size * self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'w|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._pen_size)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_state(self, pen_state=None, share=True):
        ''' Set the pen state (down==True) for this turtle. '''
        if pen_state is not None:
            self._pen_state = pen_state

        if self._turtles.turtle_window.sharing() and share:
            event = 'p|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              self._pen_state]))
            self._turtles.turtle_window.send_event(event)

    def set_fill(self, state=False):
        self._pen_fill = state
        if not self._pen_fill:
            self._poly_points = []

    def set_poly_points(self, poly_points=None):
        if poly_points is not None:
            self._poly_points = poly_points[:]

    def start_fill(self):
        self._pen_fill = True
        self._poly_points = []

    def stop_fill(self, share=True):
        self._pen_fill = False
        if len(self._poly_points) == 0:
            return

        self._turtles.turtle_window.canvas.fill_polygon(self._poly_points)

        if self._turtles.turtle_window.sharing() and share:
            shared_poly_points = []
            for p in self._poly_points:
                x, y = self._turtles.turtle_to_screen_coordinates(
                    (p[1], p[2]))
                if p[0] in ['move', 'line']:
                    shared_poly_points.append((p[0], x, y))
                elif p[0] in ['rarc', 'larc']:
                    shared_poly_points.append((p[0], x, y, p[3], p[4], p[5]))
                event = 'F|%s' % (data_to_string(
                        [self._turtles.turtle_window.nick,
                         shared_poly_points]))
            self._turtles.turtle_window.send_event(event)
        self._poly_points = []

    def hide(self):
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self._hidden = True

    def show(self):
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self._hidden = False
        self.move_turtle_spr((self._x, self._y))
        self.set_heading(self._heading, share=False)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move_turtle(self, pos=None):
        ''' Move the turtle's position '''
        if pos is None:
            pos = self.get_xy()

        self._x, self._y = pos[0], pos[1]
        if self.spr is not None:
            self.move_turtle_spr(pos)

    def move_turtle_spr(self, pos):
        ''' Move the turtle's sprite '''
        pos = self._turtles.turtle_to_screen_coordinates(pos)

        pos[0] -= self._half_width
        pos[1] -= self._half_height

        if not self._hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move((pos[0] + self.label_xy[0],
                                       pos[1] + self.label_xy[1]))

    def right(self, degrees, share=True):
        ''' Rotate turtle clockwise '''
        try:
            self._heading += degrees
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def _draw_line(self, old, new, pendown):
        if self._pen_state and pendown:
            self._turtles.turtle_window.canvas.set_source_rgb()
            pos1 = self._turtles.turtle_to_screen_coordinates(old)
            pos2 = self._turtles.turtle_to_screen_coordinates(new)
            self._turtles.turtle_window.canvas.draw_line(pos1[0], pos1[1],
                                                         pos2[0], pos2[1])
            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', pos1[0], pos1[1]))
                self._poly_points.append(('line', pos2[0], pos2[1]))

    def forward(self, distance, share=True):
        scaled_distance = distance * self._turtles.turtle_window.coord_scale

        old = self.get_xy()
        try:
            xcor = old[0] + scaled_distance * sin(self._heading * DEGTOR)
            ycor = old[1] + scaled_distance * cos(self._heading * DEGTOR)
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._draw_line(old, (xcor, ycor), True)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'f|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              int(distance)]))
            self._turtles.turtle_window.send_event(event)

    def set_xy(self, x, y, share=True, pendown=True, dragging=False):
        old = self.get_xy()
        try:
            if dragging:
                xcor = x
                ycor = y
            else:
                xcor = x * self._turtles.turtle_window.coord_scale
                ycor = y * self._turtles.turtle_window.coord_scale
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self._draw_line(old, (xcor, ycor), pendown)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'x|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(xcor),
                                               round_int(ycor)]]))
            self._turtles.turtle_window.send_event(event)

    def arc(self, a, r, share=True):
        ''' Draw an arc '''
        if self._pen_state:
            self._turtles.turtle_window.canvas.set_source_rgb()
        try:
            if a < 0:
                pos = self.larc(-a, r)
            else:
                pos = self.rarc(a, r)
        except (TypeError, ValueError):
            debug_output('bad value sent to %s' % (__name__),
                         self._turtles.turtle_window.running_sugar)
            return

        self.move_turtle(pos)

        if self._turtles.turtle_window.sharing() and share:
            event = 'a|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(a), round_int(r)]]))
            self._turtles.turtle_window.send_event(event)

    def rarc(self, a, r):
        ''' draw a clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] + r * cos(self._heading * DEGTOR)
        cy = pos[1] - r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.rarc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', npos[0], npos[1]))
                    self._poly_points.append(('rarc', npos[0], npos[1], r,
                                              (self._heading - 180) * DEGTOR,
                                              (self._heading - 180 + a)
                                              * DEGTOR))

        self.right(a, False)
        return [cx - r * cos(self._heading * DEGTOR),
                cy + r * sin(self._heading * DEGTOR)]

    def larc(self, a, r):
        ''' draw a counter-clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] - r * cos(self._heading * DEGTOR)
        cy = pos[1] + r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.larc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', npos[0], npos[1]))
                    self._poly_points.append(('larc', npos[0], npos[1], r,
                                              (self._heading) * DEGTOR,
                                              (self._heading - a) * DEGTOR))

        self.right(-a, False)
        return [cx + r * cos(self._heading * DEGTOR),
                cy - r * sin(self._heading * DEGTOR)]

    def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
        ''' Draw a pixbuf '''

        self._turtles.turtle_window.canvas.draw_pixbuf(
            pixbuf, a, b, x, y, w, h, self._heading)

        if self._turtles.turtle_window.sharing() and share:
            if self._turtles.turtle_window.running_sugar:
                tmp_path = get_path(self._turtles.turtle_window.activity,
                                    'instance')
            else:
                tmp_path = '/tmp'
            tmp_file = os.path.join(
                get_path(self._turtles.turtle_window.activity, 'instance'),
                'tmpfile.png')
            pixbuf.save(tmp_file, 'png', {'quality': '100'})
            data = image_to_base64(tmp_file, tmp_path)
            height = pixbuf.get_height()
            width = pixbuf.get_width()

            pos = self._turtles.screen_to_turtle_coordinates((x, y))

            event = 'P|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [round_int(a), round_int(b),
                                               round_int(pos[0]),
                                               round_int(pos[1]),
                                               round_int(w), round_int(h),
                                               round_int(width),
                                               round_int(height),
                                               data]]))
            gobject.idle_add(self._turtles.turtle_window.send_event, event)

            os.remove(tmp_file)

    def draw_text(self, label, x, y, size, w, share=True):
        ''' Draw text '''
        self._turtles.turtle_window.canvas.draw_text(
            label, x, y, size, w, self._heading,
            self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'W|%s' % (data_to_string([self._turtles.turtle_window.nick,
                                              [label, round_int(x),
                                               round_int(y), round_int(size),
                                               round_int(w)]]))
            self._turtles.turtle_window.send_event(event)

    def get_name(self):
        return self._name

    def get_xy(self):
        return [self._x, self._y]
    
    def get_x(self):
        return self._x
    
    def get_y(self):
        return self._y

    def get_heading(self):
        return self._heading

    def get_color(self):
        return self._pen_color

    def get_gray(self):
        return self._pen_gray

    def get_shade(self):
        return self._pen_shade

    def get_pen_size(self):
        return self._pen_size

    def get_pen_state(self):
        return self._pen_state

    def get_fill(self):
        return self._pen_fill

    def get_poly_points(self):
        return self._poly_points

    def get_pixel(self):
        pos = self._turtles.turtle_to_screen_coordinates(self.get_xy())
        return self._turtles.turtle_window.canvas.get_pixel(pos[0], pos[1])

    def get_drag_radius(self):
        if self._drag_radius is None:
            self._calculate_sizes()
        return self._drag_radius
Beispiel #10
0
class Game():

    def __init__(self, canvas, parent=None, colors=['#A0FFA0', '#FF8080']):
        self._activity = parent
        self._colors = colors

        self._canvas = canvas
        parent.show_all()

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - (GRID_CELL_SIZE * 1.5)
        self._scale = self._height / (14.0 * DOT_SIZE * 1.2)
        self._dot_size = int(DOT_SIZE * self._scale)
        self._turtle_offset = 0
        self._space = int(self._dot_size / 5.)
        self._orientation = 0
        self.level = 0
        self.custom_strategy = None
        self.strategies = [BEGINNER_STRATEGY, INTERMEDIATE_STRATEGY,
                           EXPERT_STRATEGY, self.custom_strategy]
        self.strategy = self.strategies[self.level]
        self._timeout_id = None

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)
        self._dots = []
        for y in range(THIRTEEN):
            for x in range(THIRTEEN):
                xoffset = int((self._width - THIRTEEN * (self._dot_size + \
                                      self._space) - self._space) / 2.)
                if y % 2 == 1:
                    xoffset += int((self._dot_size + self._space) / 2.)
                if x == 0 or y == 0 or x == THIRTEEN - 1 or y == THIRTEEN - 1:
                    self._dots.append(
                        Sprite(self._sprites,
                               xoffset + x * (self._dot_size + self._space),
                               y * (self._dot_size + self._space),
                               self._new_dot('#B0B0B0')))
                else:
                    self._dots.append(
                        Sprite(self._sprites,
                               xoffset + x * (self._dot_size + self._space),
                               y * (self._dot_size + self._space),
                               self._new_dot(self._colors[FILL])))
                    self._dots[-1].type = False  # not set

        # Put a turtle at the center of the screen...
        self._turtle_images = []
        self._rotate_turtle(self._new_turtle())
        self._turtle = Sprite(self._sprites, 0, 0,
                              self._turtle_images[0])
        self._move_turtle(self._dots[int(THIRTEEN * THIRTEEN / 2)].get_xy())

        # ...and initialize.
        self._all_clear()

    def _move_turtle(self, pos):
        ''' Move turtle and add its offset '''
        self._turtle.move(pos)
        self._turtle.move_relative(
            (-self._turtle_offset, -self._turtle_offset))

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        # Clear dots
        for dot in self._dots:
            if dot.type:
                dot.type = False
                dot.set_shape(self._new_dot(self._colors[FILL]))                
            dot.set_label('')

        # Recenter the turtle
        self._move_turtle(self._dots[int(THIRTEEN * THIRTEEN / 2)].get_xy())
        self._turtle.set_shape(self._turtle_images[0])
        self._set_label('')
        if self._timeout_id is not None:
            GObject.source_remove(self._timeout_id)

    def new_game(self, saved_state=None):
        ''' Start a new game. '''
        self._all_clear()

        # Fill in a few dots to start
        for i in range(15):
            n = int(uniform(0, THIRTEEN * THIRTEEN))
            if self._dots[n].type is not None:
                self._dots[n].type = True
                self._dots[n].set_shape(self._new_dot(self._colors[STROKE]))

        # Calculate the distances to the edge
        self._initialize_weights()
        self.strategy = self.strategies[self.level]

    def _set_label(self, string):
        ''' Set the label in the toolbar or the window frame. '''
        self._activity.status.set_label(string)

    def _button_press_cb(self, win, event):
        win.grab_focus()
        x, y = map(int, event.get_coords())

        spr = self._sprites.find_sprite((x, y), inverse=True)
        if spr == None:
            return

        if spr.type is not None and not spr.type:
            spr.type = True
            spr.set_shape(self._new_dot(self._colors[STROKE]))
            self._weights[self._dots.index(spr)] = 1000
            self._test_game_over(self._move_the_turtle())
        return True

    def _find_the_turtle(self):
        turtle_pos = self._turtle.get_xy()
        turtle_dot = None
        for dot in self._dots:
            pos = dot.get_xy()
            # Turtle is offset
            if pos[0] == turtle_pos[0] + self._turtle_offset and \
               pos[1] == turtle_pos[1] + self._turtle_offset:
                turtle_dot = self._dots.index(dot)
                break
        if turtle_dot is None:
            _logger.debug('Cannot find the turtle...')
            return None
        return turtle_dot

    def _move_the_turtle(self):
        ''' Move the turtle after each click '''
        self._turtle_dot = self._find_the_turtle()
        if self._turtle_dot is None:
            return

        # Given the col and row of the turtle, do something
        new_dot = self._grid_to_dot(
            self._my_strategy_import(self.strategy,
                                     self._dot_to_grid(self._turtle_dot)))
        self._move_turtle(self._dots[new_dot].get_xy())
        # And set the orientation
        self._turtle.set_shape(self._turtle_images[self._orientation])

        return new_dot

    def _test_game_over(self, new_dot):
        ''' Check to see if game is over '''
        if new_dot is None:
            return
        if self._dots[new_dot].type is None:
            # Game-over feedback
            self._once_around = False
            self._happy_turtle_dance()
            return True
        c = int(self._turtle_dot / THIRTEEN) % 2
        if self._dots[
            new_dot + CIRCLE[c][0][0] + THIRTEEN * CIRCLE[c][0][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][1][0] + THIRTEEN * CIRCLE[c][1][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][2][0] + THIRTEEN * CIRCLE[c][2][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][3][0] + THIRTEEN * CIRCLE[c][3][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][4][0] + THIRTEEN * CIRCLE[c][4][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][5][0] + THIRTEEN * CIRCLE[c][5][1]].type:
           # Game-over feedback
           for dot in self._dots:
               dot.set_label(':)')
           return True
        return False

    def _grid_to_dot(self, pos):
        ''' calculate the dot index from a column and row in the grid '''
        return pos[0] + pos[1] * THIRTEEN

    def _dot_to_grid(self, dot):
        ''' calculate the grid column and row for a dot '''
        return [dot % THIRTEEN, int(dot / THIRTEEN)]

    def _happy_turtle_dance(self):
        ''' Turtle dances along the edge '''
        i = self._find_the_turtle()
        if i == 0: 
            if self._once_around:
                return
            else:
                self._once_around = True
        _logger.debug(i)
        x, y = self._dot_to_grid(i)
        if y == 0:
            x += 1
        if x == 0:
            y -= 1
        if x == THIRTEEN - 1:
            y += 1
        if y == THIRTEEN - 1:
            x -= 1
        i = self._grid_to_dot((x, y))
        self._dots[i].set_label(':)')
        self._move_turtle(self._dots[i].get_xy())
        self._orientation += 1
        self._orientation %= 6
        self._turtle.set_shape(self._turtle_images[self._orientation])
        self._timeout_id = GObject.timeout_add(250, self._happy_turtle_dance)

    def _ordered_weights(self, pos):
        ''' Returns the list of surrounding points sorted by their
        distance to the edge '''
        dots = self._surrounding_dots(pos)
        dots_and_weights = []
        for dot in dots:
            dots_and_weights.append((dot, self._weights[dot]))
        sorted_dots = sorted(dots_and_weights, key=lambda foo: foo[1])
        for i in range(6):
            dots[i] = sorted_dots[i][0]
        return dots

    def _daylight_ahead(self, pos):
        ''' Returns true if there is a straight path to the edge from
        the current position/orientation '''
        dots = self._surrounding_dots(pos)
        while True:
            dot_type = self._dots[dots[self._orientation]].type
            if dot_type is None:
                return True
            elif dot_type:
                return False
            else:  # keep looking
                pos = self._dot_to_grid(dots[self._orientation])
                dots = self._surrounding_dots(pos)

    def _surrounding_dots(self, pos):
        ''' Returns dots surrounding a position in the grid '''
        dots = []
        evenodd = pos[1] % 2
        for i in range(6):
            col = pos[0] + CIRCLE[evenodd][i][0]
            row = pos[1] + CIRCLE[evenodd][i][1]
            dots.append(self._grid_to_dot((col, row)))
        return dots

    def _initialize_weights(self):
        ''' How many steps to an edge? '''
        self._weights = []
        for d, dot in enumerate(self._dots):
            if dot.type is None:
                self._weights.append(0)
            elif dot.type:
                self._weights.append(1000)
            else:
                pos = self._dot_to_grid(d)
                pos2 = (THIRTEEN - pos[0], THIRTEEN - pos[1])
                self._weights.append(min(min(pos[0], pos2[0]),
                                         min(pos[1], pos2[1])))

    def _my_strategy_import(self, f, arg):
        ''' Run Python code passed as argument '''
        userdefined = {}
        try:
            exec f in globals(), userdefined
            return userdefined['_turtle_strategy'](self, arg)
        except ZeroDivisionError, e:
            self._set_label('Python zero-divide error: %s' % (str(e)))
        except ValueError, e:
            self._set_label('Python value error: %s' % (str(e)))
Beispiel #11
0
class Ball():
    ''' The Bounce class is used to define the ball and the user
    interaction. '''
    def __init__(self, sprites, filename):
        self._current_frame = 0
        self._frames = []  # Easter Egg animation
        self._sprites = sprites
        self.ball = Sprite(self._sprites, 0, 0,
                           svg_str_to_pixbuf(svg_from_file(filename)))

        self.ball.set_layer(3)
        self.ball.set_label_attributes(24, vert_align='top')

        ball = extract_svg_payload(file(filename, 'r'))
        for i in range(8):
            self._frames.append(
                Sprite(
                    self._sprites, 0, 0,
                    svg_str_to_pixbuf(
                        svg_header(SIZE[0], SIZE[1], 1.0) + TRANSFORMS[i] +
                        ball + PUNCTURE + AIR + '</g>' + svg_footer())))

        for frame in self._frames:
            frame.set_layer(3)
            frame.move((0, -SIZE[1]))  # move animation frames off screen

    def new_ball(self, filename):
        ''' Create a ball object and Easter Egg animation from an SVG file. '''
        self.ball.set_shape(svg_str_to_pixbuf(svg_from_file(filename)))
        ball = extract_svg_payload(file(filename, 'r'))
        for i in range(8):
            self._frames[i].set_shape(
                svg_str_to_pixbuf(
                    svg_header(SIZE[0], SIZE[1], 1.0) + TRANSFORMS[i] + ball +
                    PUNCTURE + AIR + '</g>' + svg_footer()))

    def new_ball_from_image(self, filename, save_path):
        ''' Just create a ball object from an image file '''
        if filename == '':
            _logger.debug('Image file not found.')
            return
        try:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
            if pixbuf.get_width() > pixbuf.get_height():
                size = pixbuf.get_height()
                x = int((pixbuf.get_width() - size) / 2)
            else:
                size = pixbuf.get_width()
                x = int((pixbuf.get_height() - size) / 2)
            crop = GdkPixbuf.Pixbuf.new(0, True, 8, size, size)
            pixbuf.copy_area(x, 0, size, size, crop, 0, 0)
            scale = crop.scale_simple(85, 85, GdkPixbuf.InterpType.BILINEAR)
            scale.savev(save_path, 'png', [], [])
            self.ball.set_shape(svg_str_to_pixbuf(
                generate_ball_svg(save_path)))
        except Exception as e:
            _logger.error('Could not load image from %s: %s' % (filename, e))

    def new_ball_from_fraction(self, fraction):
        ''' Create a ball with a section of size fraction. '''
        r = SIZE[0] / 2.0
        self.ball.set_shape(
            svg_str_to_pixbuf(
                svg_header(SIZE[0], SIZE[1], 1.0) +
                svg_sector(r, r + BOX[1], r - 1, 1.999 *
                           pi, COLORS[0], COLORS[1]) +
                svg_sector(r, r + BOX[1], r - 1, fraction * 2 *
                           pi, COLORS[1], COLORS[0]) +
                svg_rect(BOX[0], BOX[1], 4, 4, 0, 0, '#FFFFFF', 'none') +
                svg_footer()))

    def ball_x(self):
        return self.ball.get_xy()[0]

    def ball_y(self):
        return self.ball.get_xy()[1]

    def frame_x(self, i):
        return self._frames[i].get_xy()[0]

    def frame_y(self, i):
        return self._frames[i].get_xy()[1]

    def width(self):
        return self.ball.rect[2]

    def height(self):
        return self.ball.rect[3]

    def move_ball(self, pos):
        self.ball.move(pos)

    def move_ball_relative(self, pos):
        self.ball.move_relative(pos)

    def move_frame(self, i, pos):
        self._frames[i].move(pos)

    def move_frame_relative(self, i, pos):
        self._frames[i].move_relative(pos)

    def hide_frames(self):
        for frame in self._frames:
            frame.move((0, -SIZE[1]))  # hide the animation frames

    def next_frame(self, frame_counter):
        if frame_counter in ANIMATION:
            self._switch_frames(ANIMATION[frame_counter])
        return self._current_frame

    def _switch_frames(self, frames):
        ''' Switch between frames in the animation '''
        self.move_frame(frames[1],
                        (self.frame_x(frames[0]), self.frame_y(frames[0])))
        self.move_frame(frames[0], ((0, -SIZE[1])))  # hide the frame
        self._current_frame = frames[1]
Beispiel #12
0
class Game():
    def __init__(self, canvas, parent=None, colors=['#A0FFA0', '#FF8080']):
        self._activity = parent
        self._colors = colors

        self._canvas = canvas
        parent.show_all()

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - (GRID_CELL_SIZE * 1.5)
        self._scale = self._height / (14.0 * DOT_SIZE * 1.2)
        self._scale_gameover = self._height / (4.0 * DOT_SIZE_GAMEOVER * 1.2)
        self._dot_size = int(DOT_SIZE * self._scale)
        self._dot_size_gameover = int(DOT_SIZE_GAMEOVER * self._scale)
        self._turtle_offset = 0
        self._space = int(self._dot_size / 5.)
        self._space_gameover = int(self._dot_size_gameover / 5.)
        self._orientation = 0
        self.level = 0
        self.custom_strategy = None
        self.strategies = [
            BEGINNER_STRATEGY, INTERMEDIATE_STRATEGY, EXPERT_STRATEGY,
            self.custom_strategy
        ]
        self.strategy = self.strategies[self.level]
        self._timeout_id = None
        self.best_time = self.load_best_time()
        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)
        self._dots = []
        self._gameover = []
        self._your_time = []
        self._best_time = []
        self._win_lose = []
        for y in range(THIRTEEN):
            for x in range(THIRTEEN):
                offset_x = int((self._width - THIRTEEN * (self._dot_size + \
                                      self._space) - self._space) / 2.)
                if y % 2 == 1:
                    offset_x += int((self._dot_size + self._space) / 2.)
                if x == 0 or y == 0 or x == THIRTEEN - 1 or y == THIRTEEN - 1:
                    self._dots.append(
                        Sprite(self._sprites,
                               offset_x + x * (self._dot_size + self._space),
                               y * (self._dot_size + self._space),
                               self._new_dot('#B0B0B0', self._dot_size)))
                else:
                    self._dots.append(
                        Sprite(
                            self._sprites,
                            offset_x + x * (self._dot_size + self._space),
                            y * (self._dot_size + self._space),
                            self._new_dot(self._colors[FILL], self._dot_size)))
                    self._dots[-1].type = False  # not set

        # Put a turtle at the center of the screen...
        self._turtle_images = []
        self._rotate_turtle(self._new_turtle())
        self._turtle = Sprite(self._sprites, 0, 0, self._turtle_images[0])
        self._move_turtle(self._dots[int(THIRTEEN * THIRTEEN / 2)].get_xy())

        # ...and initialize.
        self._all_clear()

    def _move_turtle(self, pos):
        ''' Move turtle and add its offset '''
        self._turtle.move(pos)
        self._turtle.move_relative(
            (-self._turtle_offset, -self._turtle_offset))

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        # Clear dots
        for gameover_shape in self._gameover:
            gameover_shape.hide()
        for win_lose_shape in self._win_lose:
            win_lose_shape.hide()
        for your_time_shape in self._your_time:
            your_time_shape.hide()
        for highscore_shape in self._best_time:
            highscore_shape.hide()
        for dot in self._dots:
            if dot.type:
                dot.type = False
                dot.set_shape(self._new_dot(self._colors[FILL],
                                            self._dot_size))
            dot.set_label('')
            dot.set_layer(100)
        self._turtle.set_layer(100)
        # Recenter the turtle
        self._move_turtle(self._dots[int(THIRTEEN * THIRTEEN / 2)].get_xy())
        self._turtle.set_shape(self._turtle_images[0])
        self._set_label('')
        if self._timeout_id is not None:
            GLib.source_remove(self._timeout_id)
            self._timeout_id = None

    def new_game(self, saved_state=None):
        ''' Start a new game. '''
        self.gameover_flag = False
        self.game_lost = False
        self._all_clear()
        # Fill in a few dots to start
        for i in range(15):
            n = int(uniform(0, THIRTEEN * THIRTEEN))
            if self._dots[n].type is not None:
                self._dots[n].type = True
                self._dots[n].set_shape(
                    self._new_dot(self._colors[STROKE], self._dot_size))
        # Calculate the distances to the edge
        self._initialize_weights()
        self.game_start_time = time.time()
        self.strategy = self.strategies[self.level]
        self._timeout_id = None

    def _set_label(self, string):
        ''' Set the label in the toolbar or the window frame. '''
        self._activity.status.set_label(string)

    def _button_press_cb(self, win, event):
        win.grab_focus()
        x, y = list(map(int, event.get_coords()))

        spr = self._sprites.find_sprite((x, y), inverse=True)
        if spr == None:
            return

        if spr.type is not None and not spr.type:
            spr.type = True
            spr.set_shape(self._new_dot(self._colors[STROKE], self._dot_size))
            self._weights[self._dots.index(spr)] = 1000
            self._test_game_over(self._move_the_turtle())
        return True

    def _find_the_turtle(self):
        turtle_pos = self._turtle.get_xy()
        turtle_dot = None
        for dot in self._dots:
            pos = dot.get_xy()
            # Turtle is offset
            if pos[0] == turtle_pos[0] + self._turtle_offset and \
               pos[1] == turtle_pos[1] + self._turtle_offset:
                turtle_dot = self._dots.index(dot)
                break
        if turtle_dot is None:
            _logger.debug('Cannot find the turtle...')
            return None
        return turtle_dot

    def _move_the_turtle(self):
        ''' Move the turtle after each click '''
        self._turtle_dot = self._find_the_turtle()
        if self._turtle_dot is None:
            return

        # Given the col and row of the turtle, do something
        new_dot = self._grid_to_dot(
            self._my_strategy_import(self.strategy,
                                     self._dot_to_grid(self._turtle_dot)))
        self._move_turtle(self._dots[new_dot].get_xy())
        # And set the orientation
        self._turtle.set_shape(self._turtle_images[self._orientation])

        return new_dot

    def _test_game_over(self, new_dot):
        ''' Check to see if game is over '''
        if new_dot is None:
            return
        if self._dots[new_dot].type is None:
            # Game-over feedback
            self._once_around = False
            self.game_stop_time = time.time()
            self.gameover_flag = True
            self._happy_turtle_dance()
            self._timeout_id = GLib.timeout_add(10000, self._game_over)
            return True
        c = int(self._turtle_dot / THIRTEEN) % 2
        if self._dots[
            new_dot + CIRCLE[c][0][0] + THIRTEEN * CIRCLE[c][0][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][1][0] + THIRTEEN * CIRCLE[c][1][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][2][0] + THIRTEEN * CIRCLE[c][2][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][3][0] + THIRTEEN * CIRCLE[c][3][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][4][0] + THIRTEEN * CIRCLE[c][4][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][5][0] + THIRTEEN * CIRCLE[c][5][1]].type:
            # Game-over feedback
            for dot in self._dots:
                dot.set_label(':)')
                self.game_stop_time = time.time()
                self.gameover_flag = True
            self._timeout_id = GLib.timeout_add(4000, self._game_over)
            return True
        return False

    def _game_over(self):
        best_seconds = self.best_time % 60
        best_minutes = self.best_time // 60
        self.elapsed_time = int(self.game_stop_time - self.game_start_time)
        second = self.elapsed_time % 60
        minute = self.elapsed_time // 60
        for dot in self._dots:
            dot.hide()
        self._turtle.hide()

        offset_y = int(self._space_gameover / 4.)
        offset_x = int((self._width - 6 * self._dot_size_gameover -
                        5 * self._space_gameover) / 2.)
        y = 1.5
        for x in range(2, 6):
            self._gameover.append(
                Sprite(
                    self._sprites,
                    offset_x + (x - 0.50) * self._dot_size_gameover,
                    y * (self._dot_size + self._space) + offset_y,
                    self._new_dot(self._colors[FILL],
                                  self._dot_size_gameover)))
            self._gameover[-1].type = -1  # No image
            self._gameover[-1].set_label_attributes(72)
        text = ["☻", " Game ", " Over ", "☻"]
        self.rings(len(text), text, self._gameover)
        y = 4.5
        for x in range(2, 6):
            self._win_lose.append(
                Sprite(
                    self._sprites,
                    offset_x + (x - 0.50) * self._dot_size_gameover,
                    y * (self._dot_size + self._space) + offset_y,
                    self._new_dot(self._colors[FILL],
                                  self._dot_size_gameover)))
            self._win_lose[-1].type = -1  # No image
            self._win_lose[-1].set_label_attributes(72)
        text_win_best_time = ["☻", "  YOU  ", "  WON  ", "☻"]
        text_lose = ["☹", "   YOU   ", "  LOST  ", "☹"]
        text_win = ["☻", " GOOD ", "   JOB  ", "☻"]
        if self.game_lost:
            self.rings(len(text_lose), text_lose, self._win_lose)
        elif self.elapsed_time <= self.best_time:
            self.rings(len(text_win_best_time), text_win_best_time,
                       self._win_lose)
        else:
            self.rings(len(text_win), text_win, self._win_lose)
        y = 7.5
        for x in range(2, 5):
            self._your_time.append(
                Sprite(
                    self._sprites, offset_x + x * self._dot_size_gameover,
                    y * (self._dot_size + self._space),
                    self._new_dot(self._colors[FILL],
                                  self._dot_size_gameover)))
            self._your_time[-1].type = -1  # No image
            self._your_time[-1].set_label_attributes(72)
        text = [
            "  your  ", " time:  ", (' {:02d}:{:02d} '.format(minute, second))
        ]
        self.rings(len(text), text, self._your_time)
        y = 10.5
        for x in range(2, 5):
            self._best_time.append(
                Sprite(
                    self._sprites, offset_x + x * self._dot_size_gameover,
                    y * (self._dot_size + self._space),
                    self._new_dot(self._colors[FILL],
                                  self._dot_size_gameover)))
            self._best_time[-1].type = -1  # No image
            self._best_time[-1].set_label_attributes(72)
        if self.elapsed_time <= self.best_time and not self.game_lost:
            self.best_time = self.elapsed_time
            best_seconds = second
            best_minutes = minute
        text = [
            "  best  ", " time:  ",
            (' {:02d}:{:02d} '.format(best_minutes, best_seconds))
        ]
        self.rings(len(text), text, self._best_time)
        self.save_best_time()
        self._timeout_id = GLib.timeout_add(7000, self.new_game)

    def rings(self, num, text, shape):
        i = 0
        for x in range(num):
            shape[x].type = -1
            shape[x].set_shape(
                self._new_dot(self._colors[FILL], self._dot_size_gameover))
            shape[x].set_label(text[i])
            shape[x].set_layer(100)
            i += 1

    def _grid_to_dot(self, pos):
        ''' calculate the dot index from a column and row in the grid '''
        return pos[0] + pos[1] * THIRTEEN

    def _dot_to_grid(self, dot):
        ''' calculate the grid column and row for a dot '''
        return [dot % THIRTEEN, int(dot / THIRTEEN)]

    def _happy_turtle_dance(self):
        ''' Turtle dances along the edge '''
        self.game_lost = True
        i = self._find_the_turtle()
        if i == 0:
            if self._once_around:
                return
            else:
                self._once_around = True
        _logger.debug(i)
        x, y = self._dot_to_grid(i)
        if y == 0:
            x += 1
        if x == 0:
            y -= 1
        if x == THIRTEEN - 1:
            y += 1
        if y == THIRTEEN - 1:
            x -= 1
        i = self._grid_to_dot((x, y))
        self._dots[i].set_label(':)')
        self._move_turtle(self._dots[i].get_xy())
        self._orientation += 1
        self._orientation %= 6
        self._turtle.set_shape(self._turtle_images[self._orientation])
        self._timeout_id = GLib.timeout_add(250, self._happy_turtle_dance)

    def _ordered_weights(self, pos):
        ''' Returns the list of surrounding points sorted by their
        distance to the edge '''
        dots = self._surrounding_dots(pos)
        dots_and_weights = []
        for dot in dots:
            dots_and_weights.append((dot, self._weights[dot]))
        sorted_dots = sorted(dots_and_weights, key=lambda foo: foo[1])
        for i in range(6):
            dots[i] = sorted_dots[i][0]
        return dots

    def _daylight_ahead(self, pos):
        ''' Returns true if there is a straight path to the edge from
        the current position/orientation '''
        dots = self._surrounding_dots(pos)
        while True:
            dot_type = self._dots[dots[self._orientation]].type
            if dot_type is None:
                return True
            elif dot_type:
                return False
            else:  # keep looking
                pos = self._dot_to_grid(dots[self._orientation])
                dots = self._surrounding_dots(pos)

    def _surrounding_dots(self, pos):
        ''' Returns dots surrounding a position in the grid '''
        dots = []
        evenodd = pos[1] % 2
        for i in range(6):
            col = pos[0] + CIRCLE[evenodd][i][0]
            row = pos[1] + CIRCLE[evenodd][i][1]
            dots.append(self._grid_to_dot((col, row)))
        return dots

    def _initialize_weights(self):
        ''' How many steps to an edge? '''
        self._weights = []
        for d, dot in enumerate(self._dots):
            if dot.type is None:
                self._weights.append(0)
            elif dot.type:
                self._weights.append(1000)
            else:
                pos = self._dot_to_grid(d)
                pos2 = (THIRTEEN - pos[0], THIRTEEN - pos[1])
                self._weights.append(
                    min(min(pos[0], pos2[0]), min(pos[1], pos2[1])))

    def _my_strategy_import(self, f, arg):
        ''' Run Python code passed as argument '''
        userdefined = {}
        try:
            exec(f, globals(), userdefined)
            return userdefined['_turtle_strategy'](self, arg)
        except ZeroDivisionError as e:
            self._set_label('Python zero-divide error: {}'.format(e))
        except ValueError as e:
            self._set_label('Python value error: {}'.format(e))
        except SyntaxError as e:
            self._set_label('Python syntax error: {}'.format(e))
        except NameError as e:
            self._set_label('Python name error: {}'.format(e))
        except OverflowError as e:
            self._set_label('Python overflow error: {}'.format(e))
        except TypeError as e:
            self._set_label('Python type error: {}'.format(e))
        except:
            self._set_label('Python error')
        traceback.print_exc()
        return None

    def __draw_cb(self, canvas, cr):
        self._sprites.redraw_sprites(cr=cr)

    def do_expose_event(self, event):
        ''' Handle the expose-event by drawing '''
        # Restrict Cairo to the exposed area
        cr = self._canvas.window.cairo_create()
        cr.rectangle(event.area.x, event.area.y, event.area.width,
                     event.area.height)
        cr.clip()
        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        Gtk.main_quit()

    def _new_dot(self, color, dot_size):
        ''' generate a dot of a color color '''
        self._stroke = color
        self._fill = color
        self._svg_width = dot_size
        self._svg_height = dot_size
        return svg_str_to_pixbuf(
            self._header() + \
            self._circle(dot_size / 2., dot_size / 2.,
                         dot_size / 2.) + \
            self._footer())

    def _new_turtle(self):
        ''' generate a turtle '''
        self._svg_width = self._dot_size * 2
        self._svg_height = self._dot_size * 2
        self._stroke = '#101010'
        self._fill = '#404040'
        return svg_str_to_pixbuf(
            self._header() + \
            self._turtle() + \
            self._footer())

    def _rotate_turtle(self, image):
        w, h = image.get_width(), image.get_height()
        nw = nh = int(sqrt(w * w + h * h))
        for i in range(6):
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
            context = cairo.Context(surface)
            context.translate(w / 2., h / 2.)
            context.rotate((30 + i * 60) * pi / 180.)
            context.translate(-w / 2., -h / 2.)
            Gdk.cairo_set_source_pixbuf(context, image, 0, 0)
            context.rectangle(0, 0, nw, nh)
            context.fill()
            self._turtle_images.append(surface)
        self._turtle_offset = int(self._dot_size / 2.)

    def _header(self):
        return '<svg\n' + 'xmlns:svg="http://www.w3.org/2000/svg"\n' + \
            'xmlns="http://www.w3.org/2000/svg"\n' + \
            'xmlns:xlink="http://www.w3.org/1999/xlink"\n' + \
            'version="1.1"\n' +  'width="' + str(self._svg_width) +  '"\n' + \
            'height="' + str(self._svg_height) + '">\n'

    def _circle(self, r, cx, cy):
        return '<circle style="fill:' + str(self._fill) + ';stroke:' + \
            str(self._stroke) +  ';" r="' + str(r - 0.5) +  '" cx="' + \
            str(cx) + '" cy="' + str(cy) + '" />\n'

    def _footer(self):
        return '</svg>\n'

    def _turtle(self):
        svg = '<g\ntransform="scale(%.1f, %.1f)">\n' % (self._svg_width / 60.,
                                                        self._svg_height / 60.)
        svg += '%s%s%s%s%s%s%s%s' % (
            '  <path d="M 27.5 48.3 ',
            'C 26.9 48.3 26.4 48.2 25.9 48.2 L 27.2 50.5 L 28.6 48.2 ',
            'C 28.2 48.2 27.9 48.3 27.5 48.3 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 40.2 11.7 ', 'C 38.0 11.7 36.2 13.3 35.8 15.3 ',
            'C 37.7 16.7 39.3 18.4 40.5 20.5 ',
            'C 42.8 20.4 44.6 18.5 44.6 16.2 ',
            'C 44.6 13.7 42.6 11.7 40.2 11.7 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 40.7 39.9 ', 'C 39.5 42.1 37.9 44.0 35.9 45.4 ',
            'C 36.4 47.3 38.1 48.7 40.2 48.7 ',
            'C 42.6 48.7 44.6 46.7 44.6 44.3 ',
            'C 44.6 42.0 42.9 40.2 40.7 39.9 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 14.3 39.9 ', 'C 12.0 40.1 10.2 42.0 10.2 44.3 ',
            'C 10.2 46.7 12.2 48.7 14.7 48.7 ',
            'C 16.7 48.7 18.5 47.3 18.9 45.4 ',
            'C 17.1 43.9 15.5 42.1 14.3 39.9 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 19.0 15.4 ', 'C 18.7 13.3 16.9 11.7 14.7 11.7 ',
            'C 12.2 11.7 10.2 13.7 10.2 16.2 ',
            'C 10.2 18.5 12.1 20.5 14.5 20.6 ',
            'C 15.7 18.5 17.2 16.8 19.0 15.4 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 27.5 12.6 ', 'C 29.4 12.6 31.2 13.0 32.9 13.7 ',
            'C 33.7 12.6 34.1 11.3 34.1 9.9 ', 'C 34.1 6.2 31.1 3.2 27.4 3.2 ',
            'C 23.7 3.2 20.7 6.2 20.7 9.9 ',
            'C 20.7 11.3 21.2 12.7 22.0 13.7 ',
            'C 23.7 13.0 25.5 12.6 27.5 12.6 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s%s%s%s%s%s%s%s' % (
            '   <path d="M 43.1 30.4 ', 'C 43.1 35.2 41.5 39.7 38.5 43.0 ',
            'C 35.6 46.4 31.6 48.3 27.5 48.3 ',
            'C 23.4 48.3 19.4 46.4 16.5 43.0 ',
            'C 13.5 39.7 11.9 35.2 11.9 30.4 ',
            'C 11.9 20.6 18.9 12.6 27.5 12.6 ',
            'C 36.1 12.6 43.1 20.6 43.1 30.4 Z" stroke_width="3.5" ', 'fill="',
            self._fill, ';" stroke="', self._stroke, '" />\n')
        svg += '%s%s%s%s%s' % (
            '   <path d="M 25.9 33.8 L 24.3 29.1 ',
            'L 27.5 26.5 L 31.1 29.2 L 29.6 33.8 Z" stroke_width="3.5" ',
            'fill="', self._stroke, ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 27.5 41.6 ',
            'C 23.5 41.4 22.0 39.5 22.0 39.5 L 25.5 35.4 L 30.0 35.5 ',
            'L 33.1 39.7 C 33.1 39.7 30.2 41.7 27.5 41.6 Z" ',
            'stroke_width="3.5" fill="', self._stroke, ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 18.5 33.8 ',
            'C 17.6 30.9 18.6 27.0 18.6 27.0 L 22.6 29.1 L 24.1 33.8 ',
            'L 20.5 38.0 C 20.5 38.0 19.1 36.0 18.4 33.8 Z" ',
            'stroke_width="3.5" fill="', self._stroke, ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 19.5 25.1 ', 'C 19.5 25.1 20.0 23.2 22.5 21.3 ',
            'C 24.7 19.7 27.0 19.6 27.0 19.6 L 26.9 24.6 L 23.4 27.3 ',
            'L 19.5 25.1 Z" stroke_width="3.5" fill="', self._stroke,
            ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 32.1 27.8 L 28.6 25.0 ',
            'L 29 19.8 C 29 19.8 30.8 19.7 33.0 21.4 ',
            'C 35.2 23.2 36.3 26.4 36.3 26.4 L 32.1 27.8 Z" ',
            'stroke_width="3.5" fill="', self._stroke, ';" stroke="none" />\n')
        svg += '%s%s%s%s%s%s' % (
            '   <path d="M 31.3 34.0 L 32.6 29.6 ',
            'L 36.8 28.0 C 36.8 28.0 37.5 30.7 36.8 33.7 ',
            'C 36.2 36.0 34.7 38.1 34.7 38.1 L 31.3 34.0 Z" ',
            'stroke_width="3.5" fill="', self._stroke, ';" stroke="none" />\n')
        svg += '</g>\n'
        return svg

    def save_best_time(self):
        file_path = os.path.join(get_activity_root(), 'data', 'best-time')
        best_time = [180]
        if os.path.exists(file_path):
            with open(file_path, "r") as fp:
                best_time = fp.readlines()
        int_best_time = int(best_time[0])
        if not int_best_time <= self.elapsed_time and not self.game_lost:
            int_best_time = self.elapsed_time
        with open(file_path, "w") as fp:
            fp.write(str(int_best_time))

    def load_best_time(self):
        file_path = os.path.join(get_activity_root(), 'data', 'best-time')
        if os.path.exists(file_path):
            with open(file_path, "r") as fp:
                highscore = fp.readlines()
            try:
                return int(highscore[0])
            except (ValueError, IndexError) as e:
                logging.exception(e)
                return 0
        return 0
Beispiel #13
0
class Turtle:

    def __init__(self, turtles, key, turtle_colors=None):
        """ The turtle is not a block, just a sprite with an orientation """
        self.x = 0
        self.y = 0
        self.hidden = False
        self.shapes = []
        self.custom_shapes = False
        self.type = 'turtle'
        self.heading = 0
        self.pen_shade = 50
        self.pen_color = 0
        self.pen_gray = 100
        self.pen_size = 5
        self.pen_state = True

        # If the turtle key is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(key)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (color_table[fill]),
                           '#%06x' % (color_table[stroke])]
            self.shapes = generate_turtle_pixbufs(self.colors)
        else:
            self.shapes = turtles.get_pixbufs()

        if turtles.sprite_list is not None:
            self.spr = Sprite(turtles.sprite_list, 0, 0, self.shapes[0])
        else:
            self.spr = None
        turtles.add_to_dict(key, self)

    def set_shapes(self, shapes):
        """ Reskin the turtle """
        n = len(shapes)
        if n == SHAPES:
            self.shapes = shapes[:]
        else:
            if n != 1:
                _logger.debug("%d images passed to set_shapes: ignoring" % (n))
            images = [shapes[0]]
            if self.heading == 0:
                for i in range(3):
                    images.append(images[i].rotate_simple(270))
                for i in range(SHAPES):
                    j = (i + 4) % SHAPES
                    self.shapes[j] = images[int(j / 9)]
            else:
                j = int(self.heading + 5) % 360 / (360 / SHAPES)
                self.shapes[j] = images[0]
        self.custom_shapes = True
        self.show()

    def reset_shapes(self):
        """ Reset the shapes to the standard turtle """
        if self.custom_shapes:
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.custom_shapes = False

    def set_heading(self, heading):
        """ Set the turtle heading (one shape per 360/SHAPES degrees) """
        self.heading = heading
        i = (int(self.heading + 5) % 360) / (360 / SHAPES)
        if not self.hidden and self.spr is not None:
            try:
                self.spr.set_shape(self.shapes[i])
            except IndexError:
                self.spr.set_shape(self.shapes[0])

    def set_color(self, color):
        """ Set the pen color for this turtle. """
        self.pen_color = color

    def set_gray(self, gray):
        """ Set the pen gray level for this turtle. """
        self.pen_gray = gray

    def set_shade(self, shade):
        """ Set the pen shade for this turtle. """
        self.pen_shade = shade

    def set_pen_size(self, pen_size):
        """ Set the pen size for this turtle. """
        self.pen_size = pen_size

    def set_pen_state(self, pen_state):
        """ Set the pen state (down==True) for this turtle. """
        self.pen_state = pen_state

    def hide(self):
        """ Hide the turtle. """
        if self.spr is not None:
            self.spr.hide()
        self.hidden = True

    def show(self):
        """ Show the turtle. """
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self.hidden = False
        self.move((self.x, self.y))
        self.set_heading(self.heading)

    def move(self, pos):
        """ Move the turtle. """
        self.x, self.y = int(pos[0]), int(pos[1])
        if not self.hidden and self.spr is not None:
            self.spr.move(pos)
        return(self.x, self.y)

    def get_xy(self):
        """ Return the turtle's x, y coordinates. """
        return(self.x, self.y)

    def get_heading(self):
        """ Return the turtle's heading. """
        return(self.heading)

    def get_color(self):
        """ Return the turtle's color. """
        return(self.pen_color)

    def get_gray(self):
        """ Return the turtle's gray level. """
        return(self.pen_gray)

    def get_shade(self):
        """ Return the turtle's shade. """
        return(self.pen_shade)

    def get_pen_size(self):
        """ Return the turtle's pen size. """
        return(self.pen_size)

    def get_pen_state(self):
        """ Return the turtle's pen state. """
        return(self.pen_state)
Beispiel #14
0
class Game():
    def __init__(self, canvas, parent=None, colors=['#A0FFA0', '#FF8080']):
        self._activity = parent
        self._colors = colors

        self._canvas = canvas
        parent.show_all()

        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.connect("draw", self.__draw_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height() - (GRID_CELL_SIZE * 1.5)
        self._scale = self._height / (14.0 * DOT_SIZE * 1.2)
        self._dot_size = int(DOT_SIZE * self._scale)
        self._turtle_offset = 0
        self._space = int(self._dot_size / 5.)
        self._orientation = 0
        self.level = 0
        self.custom_strategy = None
        self.strategies = [
            BEGINNER_STRATEGY, INTERMEDIATE_STRATEGY, EXPERT_STRATEGY,
            self.custom_strategy
        ]
        self.strategy = self.strategies[self.level]
        self._timeout_id = None

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)
        self._dots = []
        for y in range(THIRTEEN):
            for x in range(THIRTEEN):
                xoffset = int((self._width - THIRTEEN * (self._dot_size + \
                                      self._space) - self._space) / 2.)
                if y % 2 == 1:
                    xoffset += int((self._dot_size + self._space) / 2.)
                if x == 0 or y == 0 or x == THIRTEEN - 1 or y == THIRTEEN - 1:
                    self._dots.append(
                        Sprite(self._sprites,
                               xoffset + x * (self._dot_size + self._space),
                               y * (self._dot_size + self._space),
                               self._new_dot('#B0B0B0')))
                else:
                    self._dots.append(
                        Sprite(self._sprites,
                               xoffset + x * (self._dot_size + self._space),
                               y * (self._dot_size + self._space),
                               self._new_dot(self._colors[FILL])))
                    self._dots[-1].type = False  # not set

        # Put a turtle at the center of the screen...
        self._turtle_images = []
        self._rotate_turtle(self._new_turtle())
        self._turtle = Sprite(self._sprites, 0, 0, self._turtle_images[0])
        self._move_turtle(self._dots[int(THIRTEEN * THIRTEEN / 2)].get_xy())

        # ...and initialize.
        self._all_clear()

    def _move_turtle(self, pos):
        ''' Move turtle and add its offset '''
        self._turtle.move(pos)
        self._turtle.move_relative(
            (-self._turtle_offset, -self._turtle_offset))

    def _all_clear(self):
        ''' Things to reinitialize when starting up a new game. '''
        # Clear dots
        for dot in self._dots:
            if dot.type:
                dot.type = False
                dot.set_shape(self._new_dot(self._colors[FILL]))
            dot.set_label('')

        # Recenter the turtle
        self._move_turtle(self._dots[int(THIRTEEN * THIRTEEN / 2)].get_xy())
        self._turtle.set_shape(self._turtle_images[0])
        self._set_label('')
        if self._timeout_id is not None:
            GObject.source_remove(self._timeout_id)

    def new_game(self, saved_state=None):
        ''' Start a new game. '''
        self._all_clear()

        # Fill in a few dots to start
        for i in range(15):
            n = int(uniform(0, THIRTEEN * THIRTEEN))
            if self._dots[n].type is not None:
                self._dots[n].type = True
                self._dots[n].set_shape(self._new_dot(self._colors[STROKE]))

        # Calculate the distances to the edge
        self._initialize_weights()
        self.strategy = self.strategies[self.level]

    def _set_label(self, string):
        ''' Set the label in the toolbar or the window frame. '''
        self._activity.status.set_label(string)

    def _button_press_cb(self, win, event):
        win.grab_focus()
        x, y = map(int, event.get_coords())

        spr = self._sprites.find_sprite((x, y), inverse=True)
        if spr == None:
            return

        if spr.type is not None and not spr.type:
            spr.type = True
            spr.set_shape(self._new_dot(self._colors[STROKE]))
            self._weights[self._dots.index(spr)] = 1000
            self._test_game_over(self._move_the_turtle())
        return True

    def _find_the_turtle(self):
        turtle_pos = self._turtle.get_xy()
        turtle_dot = None
        for dot in self._dots:
            pos = dot.get_xy()
            # Turtle is offset
            if pos[0] == turtle_pos[0] + self._turtle_offset and \
               pos[1] == turtle_pos[1] + self._turtle_offset:
                turtle_dot = self._dots.index(dot)
                break
        if turtle_dot is None:
            _logger.debug('Cannot find the turtle...')
            return None
        return turtle_dot

    def _move_the_turtle(self):
        ''' Move the turtle after each click '''
        self._turtle_dot = self._find_the_turtle()
        if self._turtle_dot is None:
            return

        # Given the col and row of the turtle, do something
        new_dot = self._grid_to_dot(
            self._my_strategy_import(self.strategy,
                                     self._dot_to_grid(self._turtle_dot)))
        self._move_turtle(self._dots[new_dot].get_xy())
        # And set the orientation
        self._turtle.set_shape(self._turtle_images[self._orientation])

        return new_dot

    def _test_game_over(self, new_dot):
        ''' Check to see if game is over '''
        if new_dot is None:
            return
        if self._dots[new_dot].type is None:
            # Game-over feedback
            self._once_around = False
            self._happy_turtle_dance()
            return True
        c = int(self._turtle_dot / THIRTEEN) % 2
        if self._dots[
            new_dot + CIRCLE[c][0][0] + THIRTEEN * CIRCLE[c][0][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][1][0] + THIRTEEN * CIRCLE[c][1][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][2][0] + THIRTEEN * CIRCLE[c][2][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][3][0] + THIRTEEN * CIRCLE[c][3][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][4][0] + THIRTEEN * CIRCLE[c][4][1]].type and \
           self._dots[
            new_dot + CIRCLE[c][5][0] + THIRTEEN * CIRCLE[c][5][1]].type:
            # Game-over feedback
            for dot in self._dots:
                dot.set_label(':)')
            return True
        return False

    def _grid_to_dot(self, pos):
        ''' calculate the dot index from a column and row in the grid '''
        return pos[0] + pos[1] * THIRTEEN

    def _dot_to_grid(self, dot):
        ''' calculate the grid column and row for a dot '''
        return [dot % THIRTEEN, int(dot / THIRTEEN)]

    def _happy_turtle_dance(self):
        ''' Turtle dances along the edge '''
        i = self._find_the_turtle()
        if i == 0:
            if self._once_around:
                return
            else:
                self._once_around = True
        _logger.debug(i)
        x, y = self._dot_to_grid(i)
        if y == 0:
            x += 1
        if x == 0:
            y -= 1
        if x == THIRTEEN - 1:
            y += 1
        if y == THIRTEEN - 1:
            x -= 1
        i = self._grid_to_dot((x, y))
        self._dots[i].set_label(':)')
        self._move_turtle(self._dots[i].get_xy())
        self._orientation += 1
        self._orientation %= 6
        self._turtle.set_shape(self._turtle_images[self._orientation])
        self._timeout_id = GObject.timeout_add(250, self._happy_turtle_dance)

    def _ordered_weights(self, pos):
        ''' Returns the list of surrounding points sorted by their
        distance to the edge '''
        dots = self._surrounding_dots(pos)
        dots_and_weights = []
        for dot in dots:
            dots_and_weights.append((dot, self._weights[dot]))
        sorted_dots = sorted(dots_and_weights, key=lambda foo: foo[1])
        for i in range(6):
            dots[i] = sorted_dots[i][0]
        return dots

    def _daylight_ahead(self, pos):
        ''' Returns true if there is a straight path to the edge from
        the current position/orientation '''
        dots = self._surrounding_dots(pos)
        while True:
            dot_type = self._dots[dots[self._orientation]].type
            if dot_type is None:
                return True
            elif dot_type:
                return False
            else:  # keep looking
                pos = self._dot_to_grid(dots[self._orientation])
                dots = self._surrounding_dots(pos)

    def _surrounding_dots(self, pos):
        ''' Returns dots surrounding a position in the grid '''
        dots = []
        evenodd = pos[1] % 2
        for i in range(6):
            col = pos[0] + CIRCLE[evenodd][i][0]
            row = pos[1] + CIRCLE[evenodd][i][1]
            dots.append(self._grid_to_dot((col, row)))
        return dots

    def _initialize_weights(self):
        ''' How many steps to an edge? '''
        self._weights = []
        for d, dot in enumerate(self._dots):
            if dot.type is None:
                self._weights.append(0)
            elif dot.type:
                self._weights.append(1000)
            else:
                pos = self._dot_to_grid(d)
                pos2 = (THIRTEEN - pos[0], THIRTEEN - pos[1])
                self._weights.append(
                    min(min(pos[0], pos2[0]), min(pos[1], pos2[1])))

    def _my_strategy_import(self, f, arg):
        ''' Run Python code passed as argument '''
        userdefined = {}
        try:
            exec f in globals(), userdefined
            return userdefined['_turtle_strategy'](self, arg)
        except ZeroDivisionError, e:
            self._set_label('Python zero-divide error: %s' % (str(e)))
        except ValueError, e:
            self._set_label('Python value error: %s' % (str(e)))
Beispiel #15
0
class Ball():
    ''' The Bounce class is used to define the ball and the user
    interaction. '''

    def __init__(self, sprites, filename):
        self._current_frame = 0
        self._frames = []  # Easter Egg animation
        self._sprites = sprites
        self.ball = Sprite(self._sprites, 0, 0, svg_str_to_pixbuf(
            svg_from_file(filename)))

        self.ball.set_layer(3)
        self.ball.set_label_attributes(24, vert_align='top')

        ball = extract_svg_payload(file(filename, 'r'))
        for i in range(8):
            self._frames.append(Sprite(
                self._sprites, 0, 0, svg_str_to_pixbuf(
                    svg_header(SIZE[0], SIZE[1], 1.0) + TRANSFORMS[i] +
                    ball + PUNCTURE + AIR + '</g>' + svg_footer())))

        for frame in self._frames:
            frame.set_layer(3)
            frame.move((0, -SIZE[1]))  # move animation frames off screen

    def new_ball(self, filename):
        ''' Create a ball object and Easter Egg animation from an SVG file. '''
        self.ball.set_shape(svg_str_to_pixbuf(svg_from_file(filename)))
        ball = extract_svg_payload(file(filename, 'r'))
        for i in range(8):
            self._frames[i].set_shape(svg_str_to_pixbuf(
                svg_header(SIZE[0], SIZE[1], 1.0) + TRANSFORMS[i] +
                ball + PUNCTURE + AIR + '</g>' + svg_footer()))

    def new_ball_from_image(self, filename, save_path):
        ''' Just create a ball object from an image file '''
        if filename == '':
            _logger.debug('Image file not found.')
            return
        try:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
            if pixbuf.get_width() > pixbuf.get_height():
                size = pixbuf.get_height()
                x = int((pixbuf.get_width() - size) / 2)
            else:
                size = pixbuf.get_width()
                x = int((pixbuf.get_height() - size) / 2)
            crop = GdkPixbuf.Pixbuf.new(0, True, 8, size, size)
            pixbuf.copy_area(x, 0, size, size, crop, 0, 0)
            scale = crop.scale_simple(85, 85, GdkPixbuf.InterpType.BILINEAR)
            scale.savev(save_path, 'png', [], [])
            self.ball.set_shape(
                svg_str_to_pixbuf(generate_ball_svg(save_path)))
        except Exception as e:
            _logger.error('Could not load image from %s: %s' % (filename, e))

    def new_ball_from_fraction(self, fraction):
        ''' Create a ball with a section of size fraction. '''
        r = SIZE[0] / 2.0
        self.ball.set_shape(svg_str_to_pixbuf(
            svg_header(SIZE[0], SIZE[1], 1.0) +
            svg_sector(r, r + BOX[1], r - 1, 1.999 * pi,
                       COLORS[0], COLORS[1]) +
            svg_sector(r, r + BOX[1], r - 1, fraction * 2 * pi,
                       COLORS[1], COLORS[0]) +
            svg_rect(BOX[0], BOX[1], 4, 4, 0, 0, '#FFFFFF', 'none') +
            svg_footer()))

    def ball_x(self):
        return self.ball.get_xy()[0]

    def ball_y(self):
        return self.ball.get_xy()[1]

    def frame_x(self, i):
        return self._frames[i].get_xy()[0]

    def frame_y(self, i):
        return self._frames[i].get_xy()[1]

    def width(self):
        return self.ball.rect[2]

    def height(self):
        return self.ball.rect[3]

    def move_ball(self, pos):
        self.ball.move(pos)

    def move_ball_relative(self, pos):
        self.ball.move_relative(pos)

    def move_frame(self, i, pos):
        self._frames[i].move(pos)

    def move_frame_relative(self, i, pos):
        self._frames[i].move_relative(pos)

    def hide_frames(self):
        for frame in self._frames:
            frame.move((0, -SIZE[1]))  # hide the animation frames

    def next_frame(self, frame_counter):
        if frame_counter in ANIMATION:
            self._switch_frames(ANIMATION[frame_counter])
        return self._current_frame

    def _switch_frames(self, frames):
        ''' Switch between frames in the animation '''
        self.move_frame(frames[1], (self.frame_x(frames[0]),
                                    self.frame_y(frames[0])))
        self.move_frame(frames[0], ((0, -SIZE[1])))  # hide the frame
        self._current_frame = frames[1]
class BBoardActivity(activity.Activity):
    ''' Make a slideshow from starred Journal entries. '''

    def __init__(self, handle):
        ''' Initialize the toolbars and the work surface '''
        super(BBoardActivity, self).__init__(handle)

        self.datapath = get_path(activity, 'instance')

        self._hw = get_hardware()

        self._playback_buttons = {}
        self._audio_recordings = {}
        self.colors = profile.get_color().to_string().split(',')

        self._setup_toolbars()
        self._setup_canvas()

        self.slides = []
        self._setup_workspace()

        self._buddies = [profile.get_nick_name()]
        self._setup_presence_service()

        self._thumbs = []
        self._thumbnail_mode = False

        self._recording = False
        self._grecord = None
        self._alert = None

        self._dirty = False

    def _setup_canvas(self):
        ''' Create a canvas '''
        self._canvas = gtk.DrawingArea()
        self._canvas.set_size_request(int(gtk.gdk.screen_width()),
                                      int(gtk.gdk.screen_height()))
        self._canvas.show()
        self.set_canvas(self._canvas)
        self.show_all()

        self._canvas.set_flags(gtk.CAN_FOCUS)
        self._canvas.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        self._canvas.add_events(gtk.gdk.POINTER_MOTION_MASK)
        self._canvas.add_events(gtk.gdk.BUTTON_RELEASE_MASK)
        self._canvas.add_events(gtk.gdk.KEY_PRESS_MASK)
        self._canvas.connect("expose-event", self._expose_cb)
        self._canvas.connect("button-press-event", self._button_press_cb)
        self._canvas.connect("button-release-event", self._button_release_cb)
        self._canvas.connect("motion-notify-event", self._mouse_move_cb)

    def _setup_workspace(self):
        ''' Prepare to render the datastore entries. '''

        # Use the lighter color for the text background
        if lighter_color(self.colors) == 0:
            tmp = self.colors[0]
            self.colors[0] = self.colors[1]
            self.colors[1] = tmp

        self._width = gtk.gdk.screen_width()
        self._height = gtk.gdk.screen_height()
        self._scale = gtk.gdk.screen_height() / 900.

        if not HAVE_TOOLBOX and self._hw[0:2] == 'xo':
            titlef = 18
            descriptionf = 12
        else:
            titlef = 36
            descriptionf = 24

        self._find_starred()
        for ds in self.dsobjects:
            if 'title' in ds.metadata:
                title = ds.metadata['title']
            else:
                title = None
            pixbuf = None
            media_object = False
            mimetype = None
            if 'mime_type' in ds.metadata:
                mimetype = ds.metadata['mime_type']
            if mimetype[0:5] == 'image':
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                    ds.file_path, MAXX, MAXY)
                    # ds.file_path, 300, 225)
                media_object = True
            else:
                pixbuf = get_pixbuf_from_journal(ds, MAXX, MAXY)  # 300, 225)
            if 'description' in ds.metadata:
                desc = ds.metadata['description']
            else:
                desc = None
            self.slides.append(Slide(True, ds.object_id, self.colors,
                                     title, pixbuf, desc))

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)

        self._help = Sprite(
            self._sprites,
            int((self._width - int(PREVIEWW * self._scale)) / 2),
            int(PREVIEWY * self._scale),
            gtk.gdk.pixbuf_new_from_file_at_size(
                os.path.join(activity.get_bundle_path(), 'help.png'),
                int(PREVIEWW * self._scale), int(PREVIEWH * self._scale)))
        self._help.hide()

        self._genblanks(self.colors)

        self._title = Sprite(self._sprites, 0, 0, self._title_pixbuf)
        self._title.set_label_attributes(int(titlef * self._scale),
                                         rescale=False)
        self._preview = Sprite(self._sprites,
            int((self._width - int(PREVIEWW * self._scale)) / 2),
            int(PREVIEWY * self._scale), self._preview_pixbuf)

        self._description = Sprite(self._sprites,
                                   int(DESCRIPTIONX * self._scale),
                                   int(DESCRIPTIONY * self._scale),
                                   self._desc_pixbuf)
        self._description.set_label_attributes(int(descriptionf * self._scale))

        self._my_canvas = Sprite(self._sprites, 0, 0, self._canvas_pixbuf)
        self._my_canvas.set_layer(BOTTOM)

        self._clear_screen()

        self.i = 0
        self._show_slide()

        self._playing = False
        self._rate = 10

    def _genblanks(self, colors):
        ''' Need to cache these '''
        self._title_pixbuf = svg_str_to_pixbuf(
            genblank(self._width, int(TITLEH * self._scale), colors))
        self._preview_pixbuf = svg_str_to_pixbuf(
            genblank(int(PREVIEWW * self._scale), int(PREVIEWH * self._scale),
                     colors))
        self._desc_pixbuf = svg_str_to_pixbuf(
            genblank(int(self._width - (2 * DESCRIPTIONX * self._scale)),
                     int(DESCRIPTIONH * self._scale), colors))
        self._canvas_pixbuf = svg_str_to_pixbuf(
            genblank(self._width, self._height, (colors[0], colors[0])))

    def _setup_toolbars(self):
        ''' Setup the toolbars. '''

        self.max_participants = 6

        if HAVE_TOOLBOX:
            toolbox = ToolbarBox()

            # Activity toolbar
            activity_button_toolbar = ActivityToolbarButton(self)

            toolbox.toolbar.insert(activity_button_toolbar, 0)
            activity_button_toolbar.show()

            self.set_toolbar_box(toolbox)
            toolbox.show()
            self.toolbar = toolbox.toolbar

            self.record_toolbar = gtk.Toolbar()
            record_toolbar_button = ToolbarButton(
                label=_('Record a sound'),
                page=self.record_toolbar,
                icon_name='media-audio')
            self.record_toolbar.show_all()
            record_toolbar_button.show()
            toolbox.toolbar.insert(record_toolbar_button, -1)
        else:
            # Use pre-0.86 toolbar design
            primary_toolbar = gtk.Toolbar()
            toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(toolbox)
            toolbox.add_toolbar(_('Page'), primary_toolbar)
            self.record_toolbar = gtk.Toolbar()
            toolbox.add_toolbar(_('Record'), self.record_toolbar)
            toolbox.show()
            toolbox.set_current_toolbar(1)
            self.toolbar = primary_toolbar

        self._prev_button = button_factory(
            'go-previous-inactive', self.toolbar, self._prev_cb,
            tooltip=_('Prev slide'), accelerator='<Ctrl>P')

        self._next_button = button_factory(
            'go-next', self.toolbar, self._next_cb,
            tooltip=_('Next slide'), accelerator='<Ctrl>N')


        separator_factory(self.toolbar)

        slide_button = radio_factory('slide-view', self.toolbar,
                                     self._slides_cb, group=None,
                                     tooltip=_('Slide view'))
        radio_factory('thumbs-view', self.toolbar, self._thumbs_cb,
                      tooltip=_('Thumbnail view'),
                      group=slide_button)

        button_factory('view-fullscreen', self.toolbar,
                       self.do_fullscreen_cb, tooltip=_('Fullscreen'),
                       accelerator='<Alt>Return')

        separator_factory(self.toolbar)

        journal_button = button_factory(
            'write-journal', self.toolbar, self._do_journal_cb,
            tooltip=_('Update description'))
        self._palette = journal_button.get_palette()
        msg_box = gtk.HBox()

        sw = gtk.ScrolledWindow()
        sw.set_size_request(int(gtk.gdk.screen_width() / 2),
                            2 * style.GRID_CELL_SIZE)
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self._text_view = gtk.TextView()
        self._text_view.set_left_margin(style.DEFAULT_PADDING)
        self._text_view.set_right_margin(style.DEFAULT_PADDING)
        self._text_view.set_wrap_mode(gtk.WRAP_WORD_CHAR)
        self._text_view.connect('focus-out-event',
                               self._text_view_focus_out_event_cb)
        sw.add(self._text_view)
        sw.show()
        msg_box.pack_start(sw, expand=False)
        msg_box.show_all()

        self._palette.set_content(msg_box)

        label_factory(self.record_toolbar, _('Record a sound') + ':')
        self._record_button = button_factory(
            'media-record', self.record_toolbar,
            self._record_cb, tooltip=_('Start recording'))

        separator_factory(self.record_toolbar)

        # Look to see if we have audio previously recorded
        obj_id = self._get_audio_obj_id()
        dsobject = self._search_for_audio_note(obj_id)
        if dsobject is not None:
            _logger.debug('Found previously recorded audio')
            self._add_playback_button(profile.get_nick_name(),
                                      self.colors,
                                      dsobject.file_path)

        if HAVE_TOOLBOX:
            button_factory('system-restart', activity_button_toolbar,
                           self._resend_cb, tooltip=_('Refresh'))
            separator_factory(activity_button_toolbar)
            self._save_pdf = button_factory(
                'save-as-pdf', activity_button_toolbar,
                self._save_as_pdf_cb, tooltip=_('Save as PDF'))
        else:
            separator_factory(self.toolbar)
            self._save_pdf = button_factory(
                'save-as-pdf', self.toolbar,
                self._save_as_pdf_cb, tooltip=_('Save as PDF'))

        if HAVE_TOOLBOX:
            separator_factory(toolbox.toolbar, True, False)

            stop_button = StopButton(self)
            stop_button.props.accelerator = '<Ctrl>q'
            toolbox.toolbar.insert(stop_button, -1)
            stop_button.show()

    def _do_journal_cb(self, button):
        self._dirty = True
        if self._palette:
            if not self._palette.is_up():
                self._palette.popup(immediate=True,
                                    state=self._palette.SECONDARY)
            else:
                self._palette.popdown(immediate=True)
            return

    def _text_view_focus_out_event_cb(self, widget, event):
        buffer = self._text_view.get_buffer()
        start_iter = buffer.get_start_iter()
        end_iter = buffer.get_end_iter()
        self.slides[self.i].desc = buffer.get_text(start_iter, end_iter)
        self._show_slide()

    def _destroy_cb(self, win, event):
        ''' Clean up on the way out. '''
        gtk.main_quit()

    def _find_starred(self):
        ''' Find all the favorites in the Journal. '''
        self.dsobjects, nobjects = datastore.find({'keep': '1'})
        _logger.debug('found %d starred items', nobjects)

    def _prev_cb(self, button=None):
        ''' The previous button has been clicked; goto previous slide. '''
        if self.i > 0:
            self.i -= 1
            self._show_slide(direction=-1)

    def _next_cb(self, button=None):
        ''' The next button has been clicked; goto next slide. '''
        if self.i < len(self.slides) - 1:
            self.i += 1
            self._show_slide()

    def _save_as_pdf_cb(self, button=None):
        ''' Export an PDF version of the slideshow to the Journal. '''
        _logger.debug('saving to PDF...')
        if 'description' in self.metadata:
            tmp_file = save_pdf(self, self._buddies,
                                description=self.metadata['description'])
        else:
            tmp_file = save_pdf(self, self._buddies)
        _logger.debug('copying PDF file to Journal...')
        dsobject = datastore.create()
        dsobject.metadata['title'] = profile.get_nick_name() + ' ' + \
                                     _('Bboard')
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'application/pdf'
        dsobject.set_file_path(tmp_file)
        dsobject.metadata['activity'] = 'org.laptop.sugar.ReadActivity'
        datastore.write(dsobject)
        dsobject.destroy()
        return

    def _clear_screen(self):
        ''' Clear the screen to the darker of the two user colors. '''
        self._title.hide()
        self._preview.hide()
        self._description.hide()
        if hasattr(self, '_thumbs'):
            for thumbnail in self._thumbs:
                thumbnail[0].hide()
        self.invalt(0, 0, self._width, self._height)

        # Reset drag settings
        self._press = None
        self._release = None
        self._dragpos = [0, 0]
        self._total_drag = [0, 0]
        self.last_spr_moved = None

    def _update_colors(self):
        ''' Match the colors to those of the slide originator. '''
        if len(self.slides) == 0:
            return
        self._genblanks(self.slides[self.i].colors)
        self._title.set_image(self._title_pixbuf)
        self._preview.set_image(self._preview_pixbuf)
        self._description.set_image(self._desc_pixbuf)
        self._my_canvas.set_image(self._canvas_pixbuf)

    def _show_slide(self, direction=1):
        ''' Display a title, preview image, and decription for slide. '''
        self._clear_screen()
        self._update_colors()

        if len(self.slides) == 0:
            self._prev_button.set_icon('go-previous-inactive')
            self._next_button.set_icon('go-next-inactive')
            self._description.set_label(
                _('Do you have any items in your Journal starred?'))
            self._help.set_layer(TOP)
            self._description.set_layer(MIDDLE)
            return

        if self.i == 0:
            self._prev_button.set_icon('go-previous-inactive')
        else:
            self._prev_button.set_icon('go-previous')
        if self.i == len(self.slides) - 1:
            self._next_button.set_icon('go-next-inactive')
        else:
            self._next_button.set_icon('go-next')

        pixbuf = self.slides[self.i].pixbuf
        if pixbuf is not None:
            self._preview.set_shape(pixbuf.scale_simple(
                    int(PREVIEWW * self._scale),
                    int(PREVIEWH * self._scale),
                    gtk.gdk.INTERP_NEAREST))
            self._preview.set_layer(MIDDLE)
        else:
            if self._preview is not None:
                self._preview.hide()

        self._title.set_label(self.slides[self.i].title)
        self._title.set_layer(MIDDLE)

        if self.slides[self.i].desc is not None:
            self._description.set_label(self.slides[self.i].desc)
            self._description.set_layer(MIDDLE)
            text_buffer = gtk.TextBuffer()
            text_buffer.set_text(self.slides[self.i].desc)
            self._text_view.set_buffer(text_buffer)
        else:
            self._description.set_label('')
            self._description.hide()

    def _add_playback_button(self, nick, colors, audio_file):
        ''' Add a toolbar button for this audio recording '''
        if nick not in self._playback_buttons:
            self._playback_buttons[nick] = button_factory(
                'xo-chat',  self.record_toolbar,
                self._playback_recording_cb, cb_arg=nick,
                tooltip=_('Audio recording by %s') % (nick))
            xocolor = XoColor('%s,%s' % (colors[0], colors[1]))
            icon = Icon(icon_name='xo-chat', xo_color=xocolor)
            icon.show()
            self._playback_buttons[nick].set_icon_widget(icon)
            self._playback_buttons[nick].show()
        self._audio_recordings[nick] = audio_file

    def _slides_cb(self, button=None):
        if self._thumbnail_mode:
            self._thumbnail_mode = False
            self.i = self._current_slide
            self._show_slide()

    def _thumbs_cb(self, button=None):
        ''' Toggle between thumbnail view and slideshow view. '''
        if not self._thumbnail_mode:
            self._current_slide = self.i
            self._thumbnail_mode = True
            self._clear_screen()

            self._prev_button.set_icon('go-previous-inactive')
            self._next_button.set_icon('go-next-inactive')

            n = int(ceil(sqrt(len(self.slides))))
            if n > 0:
                w = int(self._width / n)
            else:
                w = self._width
            h = int(w * 0.75)  # maintain 4:3 aspect ratio
            x_off = int((self._width - n * w) / 2)
            x = x_off
            y = 0
            self._thumbs = []
            for i in range(len(self.slides)):
                self._show_thumb(i, x, y, w, h)
                x += w
                if x + w > self._width:
                    x = x_off
                    y += h
            self.i = 0  # Reset position in slideshow to the beginning
        return False

    def _show_thumb(self, i, x, y, w, h):
        ''' Display a preview image and title as a thumbnail. '''
        pixbuf = self.slides[i].pixbuf
        if pixbuf is not None:
            pixbuf_thumb = pixbuf.scale_simple(
                int(w), int(h), gtk.gdk.INTERP_TILES)
        else:
            pixbuf_thumb = svg_str_to_pixbuf(
                genblank(int(w), int(h), self.slides[i].colors))
        # Create a Sprite for this thumbnail
        self._thumbs.append([Sprite(self._sprites, x, y, pixbuf_thumb),
                             x, y, i])
        self._thumbs[i][0].set_image(
            svg_str_to_pixbuf(svg_rectangle(int(w), int(h),
                                            self.slides[i].colors)), i=1)
        self._thumbs[i][0].set_layer(TOP)

    def _expose_cb(self, win, event):
        ''' Callback to handle window expose events '''
        self.do_expose_event(event)
        return True

    # Handle the expose-event by drawing
    def do_expose_event(self, event):

        # Create the cairo context
        cr = self.canvas.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()

        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def write_file(self, file_path):
        ''' Clean up '''
        if self._dirty:
            self._save_descriptions_cb()
            self._dirty = False
        if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
            os.remove(os.path.join(self.datapath, 'output.ogg'))

    def do_fullscreen_cb(self, button):
        ''' Hide the Sugar toolbars. '''
        self.fullscreen()

    def invalt(self, x, y, w, h):
        ''' Mark a region for refresh '''
        self._canvas.window.invalidate_rect(
            gtk.gdk.Rectangle(int(x), int(y), int(w), int(h)), False)

    def _spr_to_thumb(self, spr):
        ''' Find which entry in the thumbnails table matches spr. '''
        for i, thumb in enumerate(self._thumbs):
            if spr == thumb[0]:
                return i
        return -1

    def _spr_is_thumbnail(self, spr):
        ''' Does spr match an entry in the thumbnails table? '''
        if self._spr_to_thumb(spr) == -1:
            return False
        else:
            return True

    def _button_press_cb(self, win, event):
        ''' The mouse button was pressed. Is it on a thumbnail sprite? '''
        win.grab_focus()
        x, y = map(int, event.get_coords())

        self._dragpos = [x, y]
        self._total_drag = [0, 0]

        spr = self._sprites.find_sprite((x, y))
        self._press = None
        self._release = None

        # Are we clicking on a thumbnail?
        if not self._spr_is_thumbnail(spr):
            return False

        self.last_spr_moved = spr
        self._press = spr
        self._press.set_layer(DRAG)
        return False

    def _mouse_move_cb(self, win, event):
        """ Drag a thumbnail with the mouse. """
        spr = self._press
        if spr is None:
            self._dragpos = [0, 0]
            return False
        win.grab_focus()
        x, y = map(int, event.get_coords())
        dx = x - self._dragpos[0]
        dy = y - self._dragpos[1]
        spr.move_relative([dx, dy])
        # Also move the star
        self._dragpos = [x, y]
        self._total_drag[0] += dx
        self._total_drag[1] += dy
        return False

    def _button_release_cb(self, win, event):
        ''' Button event is used to swap slides or goto next slide. '''
        win.grab_focus()
        self._dragpos = [0, 0]
        x, y = map(int, event.get_coords())

        if self._thumbnail_mode:
            if self._press is None:
                return
            # Drop the dragged thumbnail below the other thumbnails so
            # that you can find the thumbnail beneath it.
            self._press.set_layer(UNDRAG)
            i = self._spr_to_thumb(self._press)
            spr = self._sprites.find_sprite((x, y))
            if self._spr_is_thumbnail(spr):
                self._release = spr
                # If we found a thumbnail and it is not the one we
                # dragged, swap their positions.
                if not self._press == self._release:
                    j = self._spr_to_thumb(self._release)
                    self._thumbs[i][0] = self._release
                    self._thumbs[j][0] = self._press
                    tmp = self.slides[i]
                    self.slides[i] = self.slides[j]
                    self.slides[j] = tmp
                    self._thumbs[j][0].move((self._thumbs[j][1],
                                             self._thumbs[j][2]))
            self._thumbs[i][0].move((self._thumbs[i][1], self._thumbs[i][2]))
            self._press.set_layer(TOP)
            self._press = None
            self._release = None
        else:
            self._next_cb()
        return False

    def _unit_combo_cb(self, arg=None):
        ''' Read value of predefined conversion factors from combo box '''
        if hasattr(self, '_unit_combo'):
            active = self._unit_combo.get_active()
            if active in UNIT_DICTIONARY:
                self._rate = UNIT_DICTIONARY[active][1]

    def _record_cb(self, button=None):
        ''' Start/stop audio recording '''
        if self._grecord is None:
            _logger.debug('setting up grecord')
            self._grecord = Grecord(self)
        if self._recording:  # Was recording, so stop (and save?)
            _logger.debug('recording...True. Preparing to save.')
            self._grecord.stop_recording_audio()
            self._recording = False
            self._record_button.set_icon('media-record')
            self._record_button.set_tooltip(_('Start recording'))
            _logger.debug('Autosaving recording')
            self._notify(title=_('Save recording'))
            gobject.timeout_add(100, self._wait_for_transcoding_to_finish)
        else:  # Wasn't recording, so start
            _logger.debug('recording...False. Start recording.')
            self._grecord.record_audio()
            self._recording = True
            self._record_button.set_icon('media-recording')
            self._record_button.set_tooltip(_('Stop recording'))

    def _wait_for_transcoding_to_finish(self, button=None):
        while not self._grecord.transcoding_complete():
            time.sleep(1)
        if self._alert is not None:
            self.remove_alert(self._alert)
            self._alert = None
        self._save_recording()

    def _playback_recording_cb(self, button=None, nick=profile.get_nick_name()):
        ''' Play back current recording '''
        _logger.debug('Playback current recording from %s...' % (nick))
        if nick in self._audio_recordings:
            play_audio_from_file(self._audio_recordings[nick])
        return

    def _get_audio_obj_id(self):
        ''' Find unique name for audio object '''
        if 'activity_id' in self.metadata:
            obj_id = self.metadata['activity_id']
        else:
            obj_id = _('Bulletin Board')
        _logger.debug(obj_id)
        return obj_id

    def _save_recording(self):
        if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
            _logger.debug('Saving recording to Journal...')
            obj_id = self._get_audio_obj_id()
            copyfile(os.path.join(self.datapath, 'output.ogg'),
                     os.path.join(self.datapath, '%s.ogg' % (obj_id)))
            dsobject = self._search_for_audio_note(obj_id)
            if dsobject is None:
                dsobject = datastore.create()
            if dsobject is not None:
                _logger.debug(self.dsobjects[self.i].metadata['title'])
                dsobject.metadata['title'] = _('Audio recording by %s') % \
                    (self.metadata['title'])
                dsobject.metadata['icon-color'] = \
                    profile.get_color().to_string()
                dsobject.metadata['tags'] = obj_id
                dsobject.metadata['mime_type'] = 'audio/ogg'
                dsobject.set_file_path(
                    os.path.join(self.datapath, '%s.ogg' % (obj_id)))
                datastore.write(dsobject)
                dsobject.destroy()
            self._add_playback_button(
                profile.get_nick_name(), self.colors,
                os.path.join(self.datapath, '%s.ogg' % (obj_id)))
            if hasattr(self, 'chattube') and self.chattube is not None:
                self._share_audio()
        else:
            _logger.debug('Nothing to save...')
        return

    def _search_for_audio_note(self, obj_id):
        ''' Look to see if there is already a sound recorded for this
        dsobject '''
        dsobjects, nobjects = datastore.find({'mime_type': ['audio/ogg']})
        # Look for tag that matches the target object id
        for dsobject in dsobjects:
            if 'tags' in dsobject.metadata and \
               obj_id in dsobject.metadata['tags']:
                _logger.debug('Found audio note')
                return dsobject
        return None

    def _save_descriptions_cb(self, button=None):
        ''' Find the object in the datastore and write out the changes
        to the decriptions. '''
        for s in self.slides:
            if not s.owner:
                continue
            jobject = datastore.get(s.uid)
            jobject.metadata['description'] = s.desc
            datastore.write(jobject, update_mtime=False,
                            reply_handler=self.datastore_write_cb,
                            error_handler=self.datastore_write_error_cb)

    def datastore_write_cb(self):
        pass

    def datastore_write_error_cb(self, error):
        _logger.error('datastore_write_error_cb: %r' % error)

    def _notify(self, title='', msg=''):
        ''' Notify user when saves are completed '''
        self._alert = Alert()
        self._alert.props.title = title
        self._alert.props.msg = msg
        self.add_alert(self._alert)
        self._alert.show()

    def _resend_cb(self, button=None):
        ''' Resend slides, but only of sharing '''
        if hasattr(self, 'chattube') and self.chattube is not None:
            self._share_slides()
            self._share_audio()

    # Serialize

    def _dump(self, slide):
        ''' Dump data for sharing.'''
        _logger.debug('dumping %s' % (slide.uid))
        data = [slide.uid, slide.colors, slide.title,
                pixbuf_to_base64(activity, slide.pixbuf), slide.desc]
        return self._data_dumper(data)

    def _data_dumper(self, data):
        if _OLD_SUGAR_SYSTEM:
            return json.write(data)
        else:
            io = StringIO()
            jdump(data, io)
            return io.getvalue()

    def _load(self, data):
        ''' Load game data from the journal. '''
        slide = self._data_loader(data)
        if len(slide) == 5:
            if not self._slide_search(slide[0]):
                _logger.debug('loading %s' % (slide[0]))
                self.slides.append(Slide(
                        False, slide[0], slide[1], slide[2],
                        base64_to_pixbuf(activity, slide[3]), slide[4]))

    def _slide_search(self, uid):
        ''' Is this slide in the list already? '''
        for slide in self.slides:
            if slide.uid == uid:
                _logger.debug('skipping %s' % (slide.uid))
                return True
        return False

    def _data_loader(self, data):
        if _OLD_SUGAR_SYSTEM:
            return json.read(data)
        else:
            io = StringIO(data)
            return jload(io)

    # Sharing-related methods

    def _setup_presence_service(self):
        ''' Setup the Presence Service. '''
        self.pservice = presenceservice.get_instance()
        self.initiating = None  # sharing (True) or joining (False)

        owner = self.pservice.get_owner()
        self.owner = owner
        self.buddies = [owner]
        self._share = ''
        self.connect('shared', self._shared_cb)
        self.connect('joined', self._joined_cb)

    def _shared_cb(self, activity):
        ''' Either set up initial share...'''
        if self._shared_activity is None:
            _logger.error('Failed to share or join activity ... \
                _shared_activity is null in _shared_cb()')
            return

        self.initiating = True
        self.waiting = False
        _logger.debug('I am sharing...')

        self.conn = self._shared_activity.telepathy_conn
        self.tubes_chan = self._shared_activity.telepathy_tubes_chan
        self.text_chan = self._shared_activity.telepathy_text_chan

        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal(
            'NewTube', self._new_tube_cb)

        _logger.debug('This is my activity: making a tube...')
        id = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube(
            SERVICE, {})

    def _joined_cb(self, activity):
        ''' ...or join an exisiting share. '''
        if self._shared_activity is None:
            _logger.error('Failed to share or join activity ... \
                _shared_activity is null in _shared_cb()')
            return

        self.initiating = False
        _logger.debug('I joined a shared activity.')

        self.conn = self._shared_activity.telepathy_conn
        self.tubes_chan = self._shared_activity.telepathy_tubes_chan
        self.text_chan = self._shared_activity.telepathy_text_chan

        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal(\
            'NewTube', self._new_tube_cb)

        _logger.debug('I am joining an activity: waiting for a tube...')
        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes(
            reply_handler=self._list_tubes_reply_cb,
            error_handler=self._list_tubes_error_cb)

        self.waiting = True

    def _list_tubes_reply_cb(self, tubes):
        ''' Reply to a list request. '''
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        ''' Log errors. '''
        _logger.error('ListTubes() failed: %s', e)

    def _new_tube_cb(self, id, initiator, type, service, params, state):
        ''' Create a new tube. '''
        _logger.debug('New tube: ID=%d initator=%d type=%d service=%s '
                     'params=%r state=%d', id, initiator, type, service,
                     params, state)

        if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE):
            if state == telepathy.TUBE_STATE_LOCAL_PENDING:
                self.tubes_chan[ \
                              telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube(id)

            tube_conn = TubeConnection(self.conn,
                self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], id, \
                group_iface=self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP])

            self.chattube = ChatTube(tube_conn, self.initiating, \
                self.event_received_cb)

            if self.waiting:
                self._send_event('j:%s' % (profile.get_nick_name()))

    def event_received_cb(self, text):
        ''' Data is passed as tuples: cmd:text '''
        _logger.debug('<<< %s' % (text[0]))
        if text[0] == 's':  # shared journal objects
            e, data = text.split(':')
            self._load(data)
        elif text[0] == 'j':  # Someone new has joined
            e, buddy = text.split(':')
            _logger.debug('%s has joined' % (buddy))
            if buddy not in self._buddies:
                self._buddies.append(buddy)
            if self.initiating:
                self._send_event('J:%s' % (profile.get_nick_name()))
                self._share_slides()
                self._share_audio()
        elif text[0] == 'J':  # Everyone must share
            e, buddy = text.split(':')
            self.waiting = False
            if buddy not in self._buddies:
                self._buddies.append(buddy)
                _logger.debug('%s has joined' % (buddy))
            self._share_slides()
            self._share_audio()
        elif text[0] == 'a':  # audio recording
            e, data = text.split(':')
            nick, colors, base64 = self._data_loader(data)
            path = os.path.join(activity.get_activity_root(),
                                'instance', 'nick.ogg')
            base64_to_file(activity, base64, path)
            self._add_playback_button(nick, colors, path)

    def _share_audio(self):
        if profile.get_nick_name() in self._audio_recordings:
            base64 = file_to_base64(
                    activity, self._audio_recordings[profile.get_nick_name()])
            gobject.idle_add(self._send_event, 'a:' + str(
                    self._data_dumper([profile.get_nick_name(),
                                       self.colors,
                                       base64])))

    def _share_slides(self):
        for s in self.slides:
            if s.owner:  # Maybe stagger the timing of the sends?
                gobject.idle_add(self._send_event, 's:' + str(self._dump(s)))
        _logger.debug('finished sharing')

    def _send_event(self, text):
        ''' Send event through the tube. '''
        if hasattr(self, 'chattube') and self.chattube is not None:
            _logger.debug('>>> %s' % (text[0]))
            self.chattube.SendText(text)
Beispiel #17
0
class Turtle:
    def __init__(self, turtles, turtle_name, turtle_colors=None):
        #print 'class Turtle taturtle.py: def __init__'
        ''' The turtle is not a block, just a sprite with an orientation '''
        self.spr = None
        self.label_block = None
        self._turtles = turtles
        self._shapes = []
        self._custom_shapes = False
        self._name = turtle_name
        self._hidden = False
        self._remote = False
        self._x = 0.0
        self._y = 0.0
        self._3Dz = 0.0
        self._3Dx = 0.0
        self._3Dy = 0.0
        self._heading = 0.0
        self._roll = 0.0
        self._pitch = 0.0
        self._direction = [0.0, 1.0, 0.0]
        self._points = [[0., 0., 0.]]
        self._points_penstate = [1]
        self._half_width = 0
        self._half_height = 0
        self._drag_radius = None
        self._pen_shade = 50
        self._pen_color = 0
        self._pen_gray = 100
        if self._turtles.turtle_window.coord_scale == 1:
            self._pen_size = 5
        else:
            self._pen_size = 1
        self._pen_state = True
        self._pen_fill = False
        self._poly_points = []

        self._prep_shapes(turtle_name, self._turtles, turtle_colors)

        # Create a sprite for the turtle in interactive mode.
        if turtles.sprite_list is not None:
            self.spr = Sprite(self._turtles.sprite_list, 0, 0, self._shapes[0])

            self._calculate_sizes()

            # Choose a random angle from which to attach the turtle
            # label to be used when sharing.
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            width = self._shapes[0].get_width()
            radius = width * 0.67
            # Restrict the angle to the sides: 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [
                    int(radius * sin(angle)),
                    int(radius * cos(angle) + width / 2.0)
                ]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [
                    int(radius * sin(angle) + width / 2.0),
                    int(radius * cos(angle) + width / 2.0)
                ]

        self._turtles.add_to_dict(turtle_name, self)

    def _calculate_sizes(self):
        #print 'taturtle.py: def _calculate_sizes'
        self._half_width = int(self.spr.rect.width / 2.0)
        self._half_height = int(self.spr.rect.height / 2.0)
        self._drag_radius = ((self._half_width * self._half_width) +
                             (self._half_height * self._half_height)) / 6

    def set_remote(self):
        #print 'taturtle.py: def set_remote'
        self._remote = True

    def get_remote(self):
        #print 'taturtle.py: def get_remote'
        return self._remote

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        #print 'taturtle.py: def _prep_shapes'
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = [
                '#%06x' % (COLOR_TABLE[fill]),
                '#%06x' % (COLOR_TABLE[stroke])
            ]
            self._shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self._shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        #print 'taturtle.py: def set_turtle_colors'
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self._shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self._heading, share=False)

    def set_shapes(self, shapes, i=0):
        #print 'taturtle.py: def set_shapes'
        ''' Reskin the turtle '''
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self._shapes):
                self._shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self._shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self._turtles.turtle_window.running_sugar)
            if self._heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2.0, nh / 2.0)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2.0, -nh / 2.0)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.0,
                                              (nh - h) / 2.0)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self._shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self._heading + 5) % 360 / (360 / SHAPES)
                self._shapes[j] = shapes[0]
        self._custom_shapes = True
        self.show()
        self._calculate_sizes()

    def reset_shapes(self):
        #print 'taturtle.py: def reset_shapes'
        ''' Reset the shapes to the standard turtle '''
        if self._custom_shapes:
            self._shapes = generate_turtle_pixbufs(self.colors)
            self._custom_shapes = False
            self._calculate_sizes()

    def _apply_rotations(self):

        self._direction = [0., 1., 0.]
        angle = self._heading * DEGTOR * -1.0
        temp = []
        temp.append((self._direction[0] * cos(angle)) -
                    (self._direction[1] * sin(angle)))
        temp.append((self._direction[0] * sin(angle)) +
                    (self._direction[1] * cos(angle)))
        temp.append(self._direction[2] * 1.0)
        self._direction = temp[:]

        angle = self._roll * DEGTOR * -1.0
        temp = []
        temp.append(self._direction[0] * 1.0)
        temp.append((self._direction[1] * cos(angle)) -
                    (self._direction[2] * sin(angle)))
        temp.append((self._direction[1] * sin(angle)) +
                    (self._direction[2] * cos(angle)))
        self._direction = temp[:]

        angle = self._pitch * DEGTOR * -1.0
        temp = []
        temp.append((self._direction[0] * cos(angle)) +
                    (self._direction[2] * sin(angle)))
        temp.append(self._direction[1] * 1.0)
        temp.append((self._direction[0] * -1.0 * sin(angle)) +
                    (self._direction[2] * cos(angle)))
        self._direction = temp[:]

    def set_heading(self, heading, share=True):
        #print 'taturtle.py: def set_heading'
        ''' Set the turtle heading (one shape per 360/SHAPES degrees) '''

        self._heading = heading
        self._heading %= 360

        self._apply_rotations()

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def set_roll(self, roll):
        ''' Set the turtle roll '''

        self._roll = roll
        self._roll %= 360

        self._apply_rotations()

    def set_pitch(self, pitch):
        ''' Set the turtle pitch '''

        self._pitch = pitch
        self._pitch %= 360

        self._apply_rotations()

    def _update_sprite_heading(self):

        #print 'taturtle.py: def _update_sprite_heading'
        ''' Update the sprite to reflect the current heading '''
        i = (int(self._heading + 5) % 360) / (360 / SHAPES)
        if not self._hidden and self.spr is not None:
            try:
                self.spr.set_shape(self._shapes[i])
            except IndexError:
                self.spr.set_shape(self._shapes[0])

    def set_color(self, color=None, share=True):
        #print 'taturtle.py: def set_color'
        ''' Set the pen color for this turtle. '''
        if isinstance(color, ColorObj):
            # See comment in tatype.py TYPE_BOX -> TYPE_COLOR
            color = color.color
        if color is None:
            color = self._pen_color
        # Special case for color blocks from CONSTANTS
        elif isinstance(color, Color):
            self.set_shade(color.shade, share)
            self.set_gray(color.gray, share)
            if color.color is not None:
                color = color.color
            else:
                color = self._pen_color

        self._pen_color = color

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'c|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_color)]))
            self._turtles.turtle_window.send_event(event)

    def set_gray(self, gray=None, share=True):
        #print 'taturtle.py: def set_gray'
        ''' Set the pen gray level for this turtle. '''
        if gray is not None:
            self._pen_gray = gray

        if self._pen_gray < 0:
            self._pen_gray = 0
        if self._pen_gray > 100:
            self._pen_gray = 100

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 'g|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_gray)]))
            self._turtles.turtle_window.send_event(event)

    def set_shade(self, shade=None, share=True):
        #print 'taturtle.py: def set_shade'
        ''' Set the pen shade for this turtle. '''
        if shade is not None:
            self._pen_shade = shade

        self._turtles.turtle_window.canvas.set_fgcolor(shade=self._pen_shade,
                                                       gray=self._pen_gray,
                                                       color=self._pen_color)

        if self._turtles.turtle_window.sharing() and share:
            event = 's|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_shade)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_size(self, pen_size=None, share=True):
        #print 'taturtle.py: def set_pen_size'
        ''' Set the pen size for this turtle. '''
        if pen_size is not None:
            self._pen_size = max(0, pen_size)

        self._turtles.turtle_window.canvas.set_pen_size(
            self._pen_size * self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'w|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._pen_size)]))
            self._turtles.turtle_window.send_event(event)

    def set_pen_state(self, pen_state=None, share=True):
        #print 'taturtle.py: def set_pen_state'
        ''' Set the pen state (down==True) for this turtle. '''
        if pen_state is not None:
            self._pen_state = pen_state

        if self._turtles.turtle_window.sharing() and share:
            event = 'p|%s' % (data_to_string(
                [self._turtles.turtle_window.nick, self._pen_state]))
            self._turtles.turtle_window.send_event(event)

    def set_fill(self, state=False):
        #print 'taturtle.py: def set_fill'
        self._pen_fill = state
        if not self._pen_fill:
            self._poly_points = []

    def set_poly_points(self, poly_points=None):
        #print 'taturtle.py: def set_poly_points'
        if poly_points is not None:
            self._poly_points = poly_points[:]

    def start_fill(self):
        #print 'taturtle.py: def start_fill'
        self._pen_fill = True
        self._poly_points = []

    def stop_fill(self, share=True):
        #print 'taturtle.py: def stop_fill'
        self._pen_fill = False
        if len(self._poly_points) == 0:
            return

        self._turtles.turtle_window.canvas.fill_polygon(self._poly_points)

        if self._turtles.turtle_window.sharing() and share:
            shared_poly_points = []
            for p in self._poly_points:
                x, y = self._turtles.turtle_to_screen_coordinates((p[1], p[2]))
                if p[0] in ['move', 'line']:
                    shared_poly_points.append((p[0], x, y))
                elif p[0] in ['rarc', 'larc']:
                    shared_poly_points.append((p[0], x, y, p[3], p[4], p[5]))
                event = 'F|%s' % (data_to_string(
                    [self._turtles.turtle_window.nick, shared_poly_points]))
            self._turtles.turtle_window.send_event(event)
        self._poly_points = []

    def hide(self):
        #print 'taturtle.py: def hide'
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self._hidden = True

    def show(self):
        #print 'taturtle.py: def show'
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self._hidden = False
        self.move_turtle_spr((self._x, self._y))
        self.set_heading(self._heading, share=False)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move_turtle(self, pos=None):
        #print 'taturtle.py: def move_turtle'
        ''' Move the turtle's position '''
        if pos is None:
            pos = self.get_xy()

        self._x, self._y = pos[0], pos[1]
        if self.spr is not None:
            self.move_turtle_spr(pos)

    def move_turtle_spr(self, pos):
        #print 'taturtle.py: def move_turtle_spr'
        ''' Move the turtle's sprite '''
        pos = self._turtles.turtle_to_screen_coordinates(pos)

        pos[0] -= self._half_width
        pos[1] -= self._half_height

        if not self._hidden and self.spr is not None:
            self.spr.move(pos)
        if self.label_block is not None:
            self.label_block.spr.move(
                (pos[0] + self.label_xy[0], pos[1] + self.label_xy[1]))

    def reset_3D(self):
        self._3Dx, self._3Dy, self._3Dz = 0.0, 0.0, 0.0
        self._direction = [0.0, 1.0, 0.0]
        self._roll, self._pitch = 0.0, 0.0
        self._points = [[0., 0., 0.]]
        self._points_penstate = [1]

    def right(self, degrees, share=True):
        #print 'taturtle.py: def right'
        ''' Rotate turtle clockwise '''
        self._heading += degrees
        self._heading %= 360

        self._update_sprite_heading()

        if self._turtles.turtle_window.sharing() and share:
            event = 'r|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 round_int(self._heading)]))
            self._turtles.turtle_window.send_event(event)

    def left(self, degrees, share=True):
        #print 'taturtle.py: def left'
        degrees = 0 - degrees
        self.right(degrees, share)

    def _draw_line(self, old, new, pendown):
        #print 'taturtle.py: def _draw_line'
        if self._pen_state and pendown:
            self._turtles.turtle_window.canvas.set_source_rgb()
            pos1 = self._turtles.turtle_to_screen_coordinates(old)
            pos2 = self._turtles.turtle_to_screen_coordinates(new)
            self._turtles.turtle_window.canvas.draw_line(
                pos1[0], pos1[1], pos2[0], pos2[1])
            if self._pen_fill:
                if self._poly_points == []:
                    self._poly_points.append(('move', pos1[0], pos1[1]))
                self._poly_points.append(('line', pos2[0], pos2[1]))

    def draw_obj(self, file_name):

        vertices = []
        lines = []
        file_handle = open(file_name, 'r')

        for line in file_handle:
            temp = line.split()
            if temp[0] == 'v':
                vertices.append(
                    [float(temp[1]),
                     float(temp[2]),
                     float(temp[3])])
            if temp[0] == 'l':
                lines.append([int(temp[1]), int(temp[2])])

        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height

        for line in lines:
            source = vertices[line[0] - 1]
            dest = vertices[line[1] - 1]

            source_point = Point3D(source[0], source[1], source[2])
            p1 = source_point.project(width, height, 512, 512)
            pair1 = [p1.x, p1.y]
            pos1 = self._turtles.screen_to_turtle_coordinates(pair1)

            dest_point = Point3D(dest[0], dest[1], dest[2])
            p2 = dest_point.project(width, height, 512, 512)
            pair2 = [p2.x, p2.y]
            pos2 = self._turtles.screen_to_turtle_coordinates(pair2)

            self._draw_line(pos1, pos2, True)
            self.move_turtle((pos2[0], pos2[1]))

        return vertices, lines

    def forward(self, distance, share=True):
        #print 'taturtle.py: def forward'
        scaled_distance = distance * self._turtles.turtle_window.coord_scale

        old = self.get_xy()  #Projected Point
        old_3D = self.get_3Dpoint()  #Actual Point

        #xcor = old[0] + scaled_distance * sin(self._heading * DEGTOR)
        #ycor = old[1] + scaled_distance * cos(self._heading * DEGTOR)

        xcor = old_3D[0] + scaled_distance * self._direction[0]
        ycor = old_3D[1] + scaled_distance * self._direction[1]
        zcor = old_3D[2] + scaled_distance * self._direction[2]

        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height

        old_point = Point3D(old_3D[0], old_3D[1],
                            old_3D[2])  # Old point as Point3D object
        p = old_point.project(width, height, 512, 512)  # Projected Old Point
        new_x, new_y = p.x, p.y
        pair1 = [new_x, new_y]
        pos1 = self._turtles.screen_to_turtle_coordinates(pair1)
        '''
        for i, val in enumerate(old_3D):
            if (abs(val) < 0.0001):
                old_3D[i] = 0.
            old_3D[i] = round(old_3D[i], 2)
        self._points.append([old_3D[0], old_3D[1], old_3D[2]])
        if (self._pen_state):
            self._points_penstate.append(1)
        else:
            self._points_penstate.append(0)
        '''

        self._3Dx, self._3Dy, self._3Dz = xcor, ycor, zcor
        self.store_data()

        new_point = Point3D(xcor, ycor, zcor)  # New point as 3D object
        p = new_point.project(width, height, 512, 512)  # Projected New Point
        new_x, new_y = p.x, p.y
        pair2 = [new_x, new_y]
        pos2 = self._turtles.screen_to_turtle_coordinates(pair2)
        #print 'new = ', new_point.x, new_point.y, new_point.z

        self._draw_line(pos1, pos2, True)
        #self.move_turtle((xcor, ycor))
        self.move_turtle((pos2[0], pos2[1]))

        if self._turtles.turtle_window.sharing() and share:
            event = 'f|%s' % (data_to_string(
                [self._turtles.turtle_window.nick,
                 int(distance)]))
            self._turtles.turtle_window.send_event(event)

    def backward(self, distance, share=True):
        #print 'taturtle.py: def backward'
        distance = 0 - distance
        self.forward(distance, share)

    def set_xy(self, x, y, share=True, pendown=True, dragging=False):
        #print 'taturtle.py: def set_xy'
        old = self.get_xy()
        if dragging:
            xcor = x
            ycor = y
        else:
            xcor = x * self._turtles.turtle_window.coord_scale
            ycor = y * self._turtles.turtle_window.coord_scale

        self._draw_line(old, (xcor, ycor), pendown)
        self.move_turtle((xcor, ycor))

        if self._turtles.turtle_window.sharing() and share:
            event = 'x|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [round_int(xcor), round_int(ycor)]
            ]))
            self._turtles.turtle_window.send_event(event)

    def set_xyz(self, x, y, z):
        ''' Set the x, y and z coordinates '''

        self._3Dx, self._3Dy, self._3Dz = x, y, z
        self.store_data()
        point_3D = Point3D(x, y, z)
        width = self._turtles.turtle_window.width
        height = self._turtles.turtle_window.height
        p = point_3D.project(width, height, 512, 512)
        new_x, new_y = p.x, p.y
        pair = [new_x, new_y]
        pos = self._turtles.screen_to_turtle_coordinates(pair)
        self.set_xy(pos[0], pos[1])

    def store_data(self):

        if (abs(self._3Dx) < 0.0001):
            self._3Dx = 0.
        if (abs(self._3Dy) < 0.0001):
            self._3Dy = 0.
        if (abs(self._3Dz) < 0.0001):
            self._3Dz = 0.
        self._3Dx = round(self._3Dx, 2)
        self._3Dy = round(self._3Dy, 2)
        self._3Dz = round(self._3Dz, 2)

        self._points.append([self._3Dx, self._3Dy, self._3Dz])
        if (self._pen_state):
            self._points_penstate.append(1)
        else:
            self._points_penstate.append(0)

    def arc(self, a, r, share=True):
        #print 'taturtle.py: def arc'
        ''' Draw an arc '''
        if self._pen_state:
            self._turtles.turtle_window.canvas.set_source_rgb()
        if a < 0:
            pos = self.larc(-a, r)
        else:
            pos = self.rarc(a, r)

        self.move_turtle(pos)

        if self._turtles.turtle_window.sharing() and share:
            event = 'a|%s' % (data_to_string([
                self._turtles.turtle_window.nick, [round_int(a),
                                                   round_int(r)]
            ]))
            self._turtles.turtle_window.send_event(event)

    def rarc(self, a, r):
        #print 'taturtle.py: def rarc'
        ''' draw a clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] + r * cos(self._heading * DEGTOR)
        cy = pos[1] - r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.rarc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                self._poly_points.append(('move', npos[0], npos[1]))
                self._poly_points.append(('rarc', npos[0], npos[1], r,
                                          (self._heading - 180) * DEGTOR,
                                          (self._heading - 180 + a) * DEGTOR))

        self.right(a, False)
        return [
            cx - r * cos(self._heading * DEGTOR),
            cy + r * sin(self._heading * DEGTOR)
        ]

    def larc(self, a, r):
        #print 'taturtle.py: def larc'
        ''' draw a counter-clockwise arc '''
        r *= self._turtles.turtle_window.coord_scale
        if r < 0:
            r = -r
            a = -a
        pos = self.get_xy()
        cx = pos[0] - r * cos(self._heading * DEGTOR)
        cy = pos[1] + r * sin(self._heading * DEGTOR)
        if self._pen_state:
            npos = self._turtles.turtle_to_screen_coordinates((cx, cy))
            self._turtles.turtle_window.canvas.larc(npos[0], npos[1], r, a,
                                                    self._heading)

            if self._pen_fill:
                self._poly_points.append(('move', npos[0], npos[1]))
                self._poly_points.append(
                    ('larc', npos[0], npos[1], r, (self._heading) * DEGTOR,
                     (self._heading - a) * DEGTOR))

        self.right(-a, False)
        return [
            cx + r * cos(self._heading * DEGTOR),
            cy - r * sin(self._heading * DEGTOR)
        ]

    def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
        #print 'taturtle.py: def draw_pixbuf'
        ''' Draw a pixbuf '''
        self._turtles.turtle_window.canvas.draw_pixbuf(pixbuf, a, b, x, y, w,
                                                       h, self._heading)

        if self._turtles.turtle_window.sharing() and share:
            if self._turtles.turtle_window.running_sugar:
                tmp_path = get_path(self._turtles.turtle_window.activity,
                                    'instance')
            else:
                tmp_path = '/tmp'
            tmp_file = os.path.join(
                get_path(self._turtles.turtle_window.activity, 'instance'),
                'tmpfile.png')
            pixbuf.save(tmp_file, 'png', {'quality': '100'})
            data = image_to_base64(tmp_file, tmp_path)
            height = pixbuf.get_height()
            width = pixbuf.get_width()

            pos = self._turtles.screen_to_turtle_coordinates((x, y))

            event = 'P|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [
                    round_int(a),
                    round_int(b),
                    round_int(pos[0]),
                    round_int(pos[1]),
                    round_int(w),
                    round_int(h),
                    round_int(width),
                    round_int(height), data
                ]
            ]))
            gobject.idle_add(self._turtles.turtle_window.send_event, event)

            os.remove(tmp_file)

    def draw_text(self, label, x, y, size, w, share=True):
        #print 'taturtle.py: def draw_text'
        ''' Draw text '''
        self._turtles.turtle_window.canvas.draw_text(
            label, x, y, size, w, self._heading,
            self._turtles.turtle_window.coord_scale)

        if self._turtles.turtle_window.sharing() and share:
            event = 'W|%s' % (data_to_string([
                self._turtles.turtle_window.nick,
                [
                    label,
                    round_int(x),
                    round_int(y),
                    round_int(size),
                    round_int(w)
                ]
            ]))
            self._turtles.turtle_window.send_event(event)

    def read_pixel(self):
        #print 'taturtle.py: def read_pixel'
        """ Read r, g, b, a from the canvas and push b, g, r to the stack """
        r, g, b, a = self.get_pixel()
        self._turtles.turtle_window.lc.heap.append(b)
        self._turtles.turtle_window.lc.heap.append(g)
        self._turtles.turtle_window.lc.heap.append(r)

    def get_color_index(self):
        #print 'taturtle.py: def get_color_index'
        r, g, b, a = self.get_pixel()
        color_index = self._turtles.turtle_window.canvas.get_color_index(
            r, g, b)
        return color_index

    def get_name(self):
        #print 'taturtle.py: def get_name'
        return self._name

    def get_xy(self):
        #print 'taturtle.py: def get_xy'
        return [self._x, self._y]

    def get_3Dpoint(self):
        return [self._3Dx, self._3Dy, self._3Dz]

    def get_x(self):
        #print 'taturtle.py: def get_x'
        return self._3Dx

    def get_y(self):
        #print 'taturtle.py: def get_y'
        return self._3Dy

    def get_z(self):
        return self._3Dz

    def get_heading(self):
        #print 'taturtle.py: def get_heading'
        return self._heading

    def get_roll(self):
        return self._roll

    def get_pitch(self):
        return self._pitch

    def get_color(self):
        #print 'taturtle.py: def get_color'
        return self._pen_color

    def get_gray(self):
        #print 'taturtle.py: def get_gray'
        return self._pen_gray

    def get_shade(self):
        #print 'taturtle.py: def get_shade'
        return self._pen_shade

    def get_pen_size(self):
        #print 'taturtle.py: def get_pen_size'
        return self._pen_size

    def get_pen_state(self):
        #print 'taturtle.py: def get_pen_state'
        return self._pen_state

    def get_fill(self):
        #print 'taturtle.py: def get_fill'
        return self._pen_fill

    def get_poly_points(self):
        #print 'taturtle.py: def get_poly_points'
        return self._poly_points

    def get_pixel(self):
        #print 'taturtle.py: def get_pixel'
        pos = self._turtles.turtle_to_screen_coordinates(self.get_xy())
        return self._turtles.turtle_window.canvas.get_pixel(pos[0], pos[1])

    def get_drag_radius(self):
        #print 'taturtle.py: def get_drag_radius'
        if self._drag_radius is None:
            self._calculate_sizes()
        return self._drag_radius
Beispiel #18
0
class Selector():
    ''' Selector class abstraction  '''

    def __init__(self, turtle_window, n):
        '''This class handles the display of palette selectors (Only relevant
        to GNOME version and very old versions of Sugar).
        '''

        self.shapes = []
        self.spr = None
        self._turtle_window = turtle_window
        self._index = n

        if not n < len(palette_names):
            # Shouldn't happen, but hey...
            debug_output('palette index %d is out of range' % n,
                         self._turtle_window.running_sugar)
            self._name = 'extras'
        else:
            self._name = palette_names[n]

        icon_pathname = None
        for path in self._turtle_window.icon_paths:
            if os.path.exists(os.path.join(path, '%soff.svg' % (self._name))):
                icon_pathname = os.path.join(path, '%soff.svg' % (self._name))
                break

        if icon_pathname is not None:
            off_shape = svg_str_to_pixbuf(svg_from_file(icon_pathname))
        else:
            off_shape = svg_str_to_pixbuf(svg_from_file(os.path.join(
                self._turtle_window.icon_paths[0], 'extrasoff.svg')))
            error_output('Unable to open %soff.svg' % (self._name),
                         self._turtle_window.running_sugar)

        icon_pathname = None
        for path in self._turtle_window.icon_paths:
            if os.path.exists(os.path.join(path, '%son.svg' % (self._name))):
                icon_pathname = os.path.join(path, '%son.svg' % (self._name))
                break

        if icon_pathname is not None:
            on_shape = svg_str_to_pixbuf(svg_from_file(icon_pathname))
        else:
            on_shape = svg_str_to_pixbuf(svg_from_file(os.path.join(
                self._turtle_window.icon_paths[0], 'extrason.svg')))
            error_output('Unable to open %son.svg' % (self._name),
                         self._turtle_window.running_sugar)

        self.shapes.append(off_shape)
        self.shapes.append(on_shape)

        x = int(ICON_SIZE * self._index)
        self.spr = Sprite(self._turtle_window.sprite_list, x, 0, off_shape)
        self.spr.type = 'selector'
        self.spr.name = self._name
        self.set_layer()

    def set_shape(self, i):
        if self.spr is not None and i in [0, 1]:
            self.spr.set_shape(self.shapes[i])

    def set_layer(self, layer=TAB_LAYER):
        if self.spr is not None:
            self.spr.set_layer(layer)

    def hide(self):
        if self.spr is not None:
            self.spr.hide()
Beispiel #19
0
class Card:
    """ Class for defining individual cards """

    def __init__(self, sprites, path, card_dim, scale, c, x, y, shape='circle'):
        """ Load a card from a precomputed SVG. """
        self.images = []
        self.orientation = 0

        if shape == 'triangle':
            file = "%s/triangle-r0-%d.svg" % (path, c)
            self.increment = 60
        elif shape == 'hexagon':
            file = "%s/hexagon-r0-%d.svg" % (path, c)
            self.increment = 120
        else:
            file = "%s/card-%d.svg" % (path, c)
            self.increment = 90

        self.images.append(load_image(file, card_dim * scale,
                                      card_dim * scale))

        if shape == 'triangle':
            file = "%s/triangle-r60-%d.svg" % (path, c)
            self.images.append(load_image(file, card_dim * scale,
                                          card_dim * scale))
            file = "%s/triangle-r120-%d.svg" % (path, c)
            self.images.append(load_image(file, card_dim * scale,
                                          card_dim * scale))
            file = "%s/triangle-r180-%d.svg" % (path, c)
            self.images.append(load_image(file, card_dim * scale,
                                          card_dim * scale))
            file = "%s/triangle-r240-%d.svg" % (path, c)
            self.images.append(load_image(file, card_dim * scale,
                                          card_dim * scale))
            file = "%s/triangle-r300-%d.svg" % (path, c)
            self.images.append(load_image(file, card_dim * scale,
                                          card_dim * scale))
        elif shape == 'hexagon':
            file = "%s/hexagon-r120-%d.svg" % (path, c)
            self.images.append(load_image(file, card_dim * scale,
                                          card_dim * scale))
            file = "%s/hexagon-r240-%d.svg" % (path, c)
            self.images.append(load_image(file, card_dim * scale,
                                          card_dim * scale))
        else:
            for r in range(3):
                self.images.append(self.images[r].rotate_simple(90))

        # create sprite from svg file
        self.spr = Sprite(sprites, x, y, self.images[0])

    def reset_image(self, tw):
        """ Reset image to orientation 0. """
        while self.orientation != 0:
            self.rotate_ccw()

    def set_orientation(self, r):
        """ Set orientation to 0, 90, 180, or 270. """
        if r in [0, 60, 90, 120, 180, 240, 270, 300]:
            while r != self.orientation:
                self.rotate_ccw()

    def rotate_180(self):
        """ Rotate a tile 180 degrees """
        print "rotate 180"
        r = 0
        while r < 180:
            self.rotate_ccw()
            r += self.increment

    def rotate_ccw(self):
        """ Set the card image to correspond to rotation r. """
        self.orientation += self.increment
        if self.orientation == 360:
            self.orientation = 0
        self.spr.set_shape(self.images[int(self.orientation/self.increment)])
Beispiel #20
0
class Card:
    """ Class for defining individual cards """
    def __init__(self,
                 sprites,
                 path,
                 card_dim,
                 scale,
                 c,
                 x,
                 y,
                 shape='circle'):
        """ Load a card from a precomputed SVG. """
        self.images = []
        self.orientation = 0

        if shape == 'triangle':
            file = "%s/triangle-r0-%d.svg" % (path, c)
            self.increment = 60
        elif shape == 'hexagon':
            file = "%s/hexagon-r0-%d.svg" % (path, c)
            self.increment = 120
        else:
            file = "%s/card-%d.svg" % (path, c)
            self.increment = 90

        self.images.append(load_image(file, card_dim * scale,
                                      card_dim * scale))

        if shape == 'triangle':
            file = "%s/triangle-r60-%d.svg" % (path, c)
            self.images.append(
                load_image(file, card_dim * scale, card_dim * scale))
            file = "%s/triangle-r120-%d.svg" % (path, c)
            self.images.append(
                load_image(file, card_dim * scale, card_dim * scale))
            file = "%s/triangle-r180-%d.svg" % (path, c)
            self.images.append(
                load_image(file, card_dim * scale, card_dim * scale))
            file = "%s/triangle-r240-%d.svg" % (path, c)
            self.images.append(
                load_image(file, card_dim * scale, card_dim * scale))
            file = "%s/triangle-r300-%d.svg" % (path, c)
            self.images.append(
                load_image(file, card_dim * scale, card_dim * scale))
        elif shape == 'hexagon':
            file = "%s/hexagon-r120-%d.svg" % (path, c)
            self.images.append(
                load_image(file, card_dim * scale, card_dim * scale))
            file = "%s/hexagon-r240-%d.svg" % (path, c)
            self.images.append(
                load_image(file, card_dim * scale, card_dim * scale))
        else:
            for r in range(3):
                self.images.append(self.images[r].rotate_simple(90))

        # create sprite from svg file
        self.spr = Sprite(sprites, x, y, self.images[0])

    def reset_image(self, tw):
        """ Reset image to orientation 0. """
        while self.orientation != 0:
            self.rotate_ccw()

    def set_orientation(self, r):
        """ Set orientation to 0, 90, 180, or 270. """
        if r in [0, 60, 90, 120, 180, 240, 270, 300]:
            while r != self.orientation:
                self.rotate_ccw()

    def rotate_180(self):
        """ Rotate a tile 180 degrees """
        print "rotate 180"
        r = 0
        while r < 180:
            self.rotate_ccw()
            r += self.increment

    def rotate_ccw(self):
        """ Set the card image to correspond to rotation r. """
        self.orientation += self.increment
        if self.orientation == 360:
            self.orientation = 0
        self.spr.set_shape(self.images[int(self.orientation / self.increment)])
Beispiel #21
0
class Turtle:

    def __init__(self, turtles, key, turtle_colors=None):
        """ The turtle is not a block, just a sprite with an orientation """
        self.x = 0.0
        self.y = 0.0
        self.hidden = False
        self.shapes = []
        self.custom_shapes = False
        self.type = 'turtle'
        self.name = key
        self.heading = 0.0
        self.pen_shade = 50
        self.pen_color = 0
        self.pen_gray = 100
        self.pen_size = 5
        self.pen_state = True
        self.label_block = None

        self._prep_shapes(key, turtles, turtle_colors)

        # Choose a random angle from which to attach the turtle label.
        if turtles.sprite_list is not None:
            self.spr = Sprite(turtles.sprite_list, 0, 0, self.shapes[0])
            angle = uniform(0, pi * 4 / 3.0)  # 240 degrees
            w = self.shapes[0].get_width()
            r = w * 0.67
            # Restrict angle the the sides 30-150; 210-330
            if angle > pi * 2 / 3.0:
                angle += pi / 2.0  # + 90
                self.label_xy = [int(r * sin(angle)),
                                 int(r * cos(angle) + w / 2.0)]
            else:
                angle += pi / 6.0  # + 30
                self.label_xy = [int(r * sin(angle) + w / 2.0),
                                 int(r * cos(angle) + w / 2.0)]
        else:
            self.spr = None
        turtles.add_to_dict(key, self)

    def _prep_shapes(self, name, turtles=None, turtle_colors=None):
        # If the turtle name is an int, we'll use a palette color as the
        # turtle color
        try:
            int_key = int(name)
            use_color_table = True
        except ValueError:
            use_color_table = False

        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
        elif use_color_table:
            fill = wrap100(int_key)
            stroke = wrap100(fill + 10)
            self.colors = ['#%06x' % (COLOR_TABLE[fill]),
                           '#%06x' % (COLOR_TABLE[stroke])]
            self.shapes = generate_turtle_pixbufs(self.colors)
        else:
            if turtles is not None:
                self.colors = DEFAULT_TURTLE_COLORS
                self.shapes = turtles.get_pixbufs()

    def set_turtle_colors(self, turtle_colors):
        ''' reset the colors of a preloaded turtle '''
        if turtle_colors is not None:
            self.colors = turtle_colors[:]
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.set_heading(self.heading)

    def set_shapes(self, shapes, i=0):
        """ Reskin the turtle """
        n = len(shapes)
        if n == 1 and i > 0:  # set shape[i]
            if i < len(self.shapes):
                self.shapes[i] = shapes[0]
        elif n == SHAPES:  # all shapes have been precomputed
            self.shapes = shapes[:]
        else:  # rotate shapes
            if n != 1:
                debug_output("%d images passed to set_shapes: ignoring" % (n),
                             self.tw.running_sugar)
            if self.heading == 0.0:  # rotate the shapes
                images = []
                w, h = shapes[0].get_width(), shapes[0].get_height()
                nw = nh = int(sqrt(w * w + h * h))
                for i in range(SHAPES):
                    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, nw, nh)
                    context = cairo.Context(surface)
                    context = gtk.gdk.CairoContext(context)
                    context.translate(nw / 2., nh / 2.)
                    context.rotate(i * 10 * pi / 180.)
                    context.translate(-nw / 2., -nh / 2.)
                    context.set_source_pixbuf(shapes[0], (nw - w) / 2.,
                                              (nh - h) / 2.)
                    context.rectangle(0, 0, nw, nh)
                    context.fill()
                    images.append(surface)
                self.shapes = images[:]
            else:  # associate shape with image at current heading
                j = int(self.heading + 5) % 360 / (360 / SHAPES)
                self.shapes[j] = shapes[0]
        self.custom_shapes = True
        self.show()

    def reset_shapes(self):
        """ Reset the shapes to the standard turtle """
        if self.custom_shapes:
            self.shapes = generate_turtle_pixbufs(self.colors)
            self.custom_shapes = False

    def set_heading(self, heading):
        """ Set the turtle heading (one shape per 360/SHAPES degrees) """
        self.heading = heading
        i = (int(self.heading + 5) % 360) / (360 / SHAPES)
        if not self.hidden and self.spr is not None:
            try:
                self.spr.set_shape(self.shapes[i])
            except IndexError:
                self.spr.set_shape(self.shapes[0])

    def set_color(self, color):
        """ Set the pen color for this turtle. """
        self.pen_color = color

    def set_gray(self, gray):
        """ Set the pen gray level for this turtle. """
        self.pen_gray = gray

    def set_shade(self, shade):
        """ Set the pen shade for this turtle. """
        self.pen_shade = shade

    def set_pen_size(self, pen_size):
        """ Set the pen size for this turtle. """
        self.pen_size = pen_size

    def set_pen_state(self, pen_state):
        """ Set the pen state (down==True) for this turtle. """
        self.pen_state = pen_state

    def hide(self):
        """ Hide the turtle. """
        if self.spr is not None:
            self.spr.hide()
        if self.label_block is not None:
            self.label_block.spr.hide()
        self.hidden = True

    def show(self):
        """ Show the turtle. """
        if self.spr is not None:
            self.spr.set_layer(TURTLE_LAYER)
            self.hidden = False
        self.move((self.x, self.y))
        self.set_heading(self.heading)
        if self.label_block is not None:
            self.label_block.spr.set_layer(TURTLE_LAYER + 1)

    def move(self, pos):
        """ Move the turtle. """
        self.x, self.y = pos[0], pos[1]
        if not self.hidden and self.spr is not None:
            self.spr.move((int(pos[0]), int(pos[1])))
        if self.label_block is not None:
            self.label_block.spr.move((int(pos[0] + self.label_xy[0]),
                                       int(pos[1] + self.label_xy[1])))
        return(self.x, self.y)

    def get_name(self):
        ''' return turtle name (key) '''
        return self.name

    def get_xy(self):
        """ Return the turtle's x, y coordinates. """
        return(self.x, self.y)

    def get_heading(self):
        """ Return the turtle's heading. """
        return(self.heading)

    def get_color(self):
        """ Return the turtle's color. """
        return(self.pen_color)

    def get_gray(self):
        """ Return the turtle's gray level. """
        return(self.pen_gray)

    def get_shade(self):
        """ Return the turtle's shade. """
        return(self.pen_shade)

    def get_pen_size(self):
        """ Return the turtle's pen size. """
        return(self.pen_size)

    def get_pen_state(self):
        """ Return the turtle's pen state. """
        return(self.pen_state)