示例#1
0
    def load_scriptable(self, sd, is_stage=False):
        if is_stage:
            scriptable = kurt.Stage(self.project)
        elif 'objName' in sd:
            scriptable = kurt.Sprite(self.project, sd["objName"])
        else:
            return self.load_watcher(sd)

        # costumes
        for cd in sd.get("costumes", []):
            image = self.read_image(cd['baseLayerID'])
            rotation_center = (cd['rotationCenterX'], cd['rotationCenterY'])

            if cd['bitmapResolution'] != 1:
                (w, h) = image.size
                w /= cd['bitmapResolution']
                h /= cd['bitmapResolution']
                image = image.resize((w, h))

                (x, y) = rotation_center
                x /= cd['bitmapResolution']
                y /= cd['bitmapResolution']
                rotation_center = (x, y)

            if 'text' in cd:
                text_layer = self.read_image(cd['textLayerID'])
                if text_layer:
                    image = image.paste(text_layer)

            scriptable.costumes.append(
                kurt.Costume(cd['costumeName'], image, rotation_center))

        # sounds
        for snd in sd.get("sounds", []):
            scriptable.sounds.append(
                kurt.Sound(
                    snd['soundName'],
                    self.read_waveform(snd['soundID'], snd['rate'],
                                       snd['sampleCount'])))

        # vars & lists
        target = self.project if is_stage else scriptable

        for vd in sd.get("variables", []):
            var = kurt.Variable(vd['value'], vd['isPersistent'])
            target.variables[vd['name']] = var

        for ld in sd.get("lists", []):
            name = ld['listName']
            target.lists[name] = kurt.List(ld['contents'], ld['isPersistent'])
            self.list_watchers.append(
                kurt.Watcher(target,
                             kurt.Block("contentsOfList:", name),
                             is_visible=ld['visible'],
                             pos=(ld['x'], ld['y'])))

        # custom blocks first
        for script_array in sd.get("scripts", []):
            if script_array[2]:
                block_array = script_array[2][0]
                if block_array[0] == 'procDef':
                    (_, spec, input_names, defaults, is_atomic) = block_array
                    cb = custom_block(spec, input_names, defaults)
                    cb.is_atomic = is_atomic
                    self.custom_blocks[spec] = cb

        # scripts
        for script_array in sd.get("scripts", []):
            scriptable.scripts.append(self.load_script(script_array))

        # comments
        blocks_by_id = []
        for script in scriptable.scripts:
            for block in list(get_blocks_by_id(script)):
                blocks_by_id.append(block)

        for comment_array in sd.get("scriptComments", []):
            (x, y, w, h, expanded, block_id, text) = comment_array
            if block_id > -1:
                blocks_by_id[block_id].comment = text
            else:
                scriptable.scripts.append(kurt.Comment(text, (x, y)))

        # sprite only
        if not is_stage:
            scriptable.position = (sd['scratchX'], sd['scratchY'])
            scriptable.direction = sd['direction']
            scriptable.rotation_style = str(sd['rotationStyle'])
            scriptable.is_draggable = sd['isDraggable']
            scriptable.is_visible = sd['visible']
            scriptable.size = sd['scale'] * 100.0

        return scriptable
import os
import sys

# try and find kurt directory
path_to_file = os.path.join(os.getcwd(), __file__)
path_to_lib = os.path.split(os.path.split(path_to_file)[0])[0]
sys.path.append(path_to_lib)
import kurt

project = kurt.Project()
testcontext = project.stage
testcontext.variables['foo'] = kurt.Variable()
testcontext.lists['positions'] = kurt.List()
project.sprites.append(kurt.Sprite(project, 'Sprite1'))

p = lambda x: kurt.text.parse(x + "\n", testcontext)
pb = lambda x: kurt.text.parse(x, testcontext)[0]

try:
    pb("a")
except SyntaxError:
    pass
else:
    raise

print pb("set foo to 4")

assert pb("set foo to 10") == kurt.Block("setVar:to:", "foo", u'10')
assert pb("set x to 4") == kurt.Block("xpos:", u'4')
assert pb("set foo to 10") == kurt.Block("setVar:to:", "foo", u'10')
assert pb("set foo to 1 * 2") == kurt.Block("setVar:to:", "foo",
def text_to_image(font, text, color):
    (w, h) = font.getsize(text)
    image = Image.new("RGB", (w, h), BG_COLOR)  #(w*2, h*2))
    draw = ImageDraw.Draw(image)
    draw.text((0, 0), text, color, font=font)
    draw.fontmode = "1"
    #image = image.resize((w, h), Image.ANTIALIAS)
    return image


project = kurt.Project()

y = 170

project.variables = {
    'Fonts.Message': kurt.Variable(),
    'Fonts.x': kurt.Variable(),
    'Fonts.y': kurt.Variable(),
    'Fonts.line_height': kurt.Variable(),
    'Fonts.Font': kurt.Variable(),
}

stage_script = """
when gf clicked
clear
set Fonts.Message to "{MESSAGE}"
set Fonts.x to (-230)
set Fonts.y to (170)
set Fonts.line_height to (::line_height::)
""".format(**locals())
    def load_scriptable(self, kurt_scriptable, v14_scriptable):
        # scripts
        kurt_scriptable.scripts = map(self.load_script, v14_scriptable.scripts)

        # fix comments
        comments = []

        blocks_by_id = []
        # A list of all the blocks in script order but reverse script
        # blocks order.
        # Used to determine which block a Comment is anchored to.
        #
        # Note that Squeak arrays are 1-based, so index with:
        #     blocks_by_id[index - 1]

        for script in kurt_scriptable.scripts:
            if isinstance(script, kurt.Comment):
                comments.append(script)
            elif isinstance(script, kurt.Script):
                for block in reversed(list(get_blocks_by_id(script))):
                    blocks_by_id.append(block)

        attached_comments = []
        for comment in comments:
            if hasattr(comment, '_anchor'):
                # Attach the comment to the right block from the given scripts.
                block = blocks_by_id[comment._anchor - 1]
                block.comment = comment.text
                attached_comments.append(comment)

        for comment in attached_comments:
            kurt_scriptable.scripts.remove(comment)

        # media
        for (name, value) in v14_scriptable.variables.items():
            kurt_scriptable.variables[name] = kurt.Variable(value)

        (images, sounds) = self.get_media(v14_scriptable)
        kurt_scriptable.costumes = map(self.load_image, images)
        kurt_scriptable.sounds = map(self.load_sound, sounds)

        # costume
        if kurt_scriptable.costumes:
            index = images.index(v14_scriptable.costume)
            kurt_scriptable.costume_index = index

        # attributes
        kurt_scriptable.volume = v14_scriptable.volume
        kurt_scriptable.tempo = v14_scriptable.tempoBPM

        # for sprites:
        if isinstance(kurt_scriptable, kurt.Sprite):
            kurt_scriptable.name = v14_scriptable.name
            kurt_scriptable.direction = v14_scriptable.rotationDegrees + 90
            kurt_scriptable.rotation_style = v14_scriptable.rotationStyle.value
            kurt_scriptable.size = v14_scriptable.scalePoint.x * 100.0
            kurt_scriptable.is_draggable = v14_scriptable.draggable
            kurt_scriptable.is_visible = (v14_scriptable.flags == 0)

            # bounds
            (x, y, right, bottom) = v14_scriptable.bounds.value
            (rx, ry) = v14_scriptable.costume.rotationCenter
            x = x + rx - 240
            y = 180 - y - ry
            kurt_scriptable.position = (x, y)