当前位置: 首页>>代码示例>>Python>>正文


Python Sprite.set_shape方法代码示例

本文整理汇总了Python中sprites.Sprite.set_shape方法的典型用法代码示例。如果您正苦于以下问题:Python Sprite.set_shape方法的具体用法?Python Sprite.set_shape怎么用?Python Sprite.set_shape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sprites.Sprite的用法示例。


在下文中一共展示了Sprite.set_shape方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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)
开发者ID:sugarlabs,项目名称:cardsort,代码行数:49,代码来源:card.py

示例2: __init__

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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]
#.........这里部分代码省略.........
开发者ID:sugarlabs,项目名称:activity-turtle-flags,代码行数:103,代码来源:taturtle.py

示例3: Selector

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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()
开发者ID:Daksh,项目名称:turtleart,代码行数:71,代码来源:taselector.py

示例4: __init__

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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))
开发者ID:erilyth,项目名称:paths,代码行数:63,代码来源:tile.py

示例5: __init__

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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)])
开发者ID:sugarlabs,项目名称:pukllanapac,代码行数:78,代码来源:card.py

示例6: __init__

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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

#.........这里部分代码省略.........
开发者ID:max630,项目名称:turtleart-hacks,代码行数:103,代码来源:taturtle.py

示例7: Ball

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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:
#.........这里部分代码省略.........
开发者ID:erilyth,项目名称:fractionbounce,代码行数:103,代码来源:ball.py

示例8: BBoardActivity

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]

#.........这里部分代码省略.........
        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)
开发者ID:walterbender,项目名称:bulletinboard,代码行数:70,代码来源:BBoardActivity.py

示例9: Game

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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)
#.........这里部分代码省略.........
开发者ID:leonardcj,项目名称:turtlepond,代码行数:103,代码来源:game.py

示例10: __init__

# 需要导入模块: from sprites import Sprite [as 别名]
# 或者: from sprites.Sprite import set_shape [as 别名]
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
#.........这里部分代码省略.........
开发者ID:walterbender,项目名称:turtleartmini,代码行数:103,代码来源:taturtle.py


注:本文中的sprites.Sprite.set_shape方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。