在Scratch中模拟自定义报告块?

时间:2015-01-14 16:50:58

标签: mit-scratch

在Scratch 2.0中,添加了对自定义堆栈块(procedures)的支持。但有没有办法用它来“抽象”返回值的逻辑?

例如,我在这里有一个天真计算指数的脚本:(view graphic representation

set [base v] to [2]
set [index v] to [3]
... // above is for initializing
set [result v] to (base)
repeat until <(index) = [1]>
  set [result v] to ((result) * (base))
  change [index v] by (-1)

我如何将此逻辑导出到“自定义记者”以重复使用?

3 个答案:

答案 0 :(得分:1)

以下是一个示例(rendered):

define split [text] by [splitter]
delete (all v) of [output list v]
set [parse v] to [0]
set [cur string v] to []
repeat until ((parse) > (length of (splitter))
   if <(letter (parse) of (text)) = (splitter)> then
      add (cur string) to [output list v]
      set [cur string v] to []
   else
      set [cur string v] to (join (cur string) (letter (parse) of (text)))
   end
end

when GF clicked
split [Hello, world! Do you like this?] by [ ] // That's a space.

// That should output a list: ["Hello,", "world!", "Do", "you", "like", "this?"]

define the answer to life
set [output var v] to (42)

when GF clicked
the answer to life
say (output var)

它展示了如何使用列表输出和变量输出。

答案 1 :(得分:0)

最简单的方法是创建一个自定义命令块,并将返回值存储在变量中。这有一些缺点,例如不允许递归调用,但在大多数情况下都有效。我还建议将块设置为在没有屏幕刷新的情况下运行。

只需像这样定义它,返回值可用result

define (base) ^ (exp)
set [index v] to (exp) // need a variable, as arguments are immutable
set [result v] to (base)
repeat until <(index) = [1]>
  set [result v] to ((result) * (base))
  change [index v] by (-1)

然后可以像:

那样调用它
when gf clicked
(4) ^ (3) // the stack block
say (join [4 ^ 3 = ] (result)) // result is set by the [()^()] block

See this in rendered ScratchBlocks.

答案 2 :(得分:0)

还有第二种更复杂的方法。它允许递归块,您可以多次运行块。我称之为堆叠方法,因为我使用列表作为堆栈。有关示例,请参阅this project that i made

此方法也不会使变量调色板混乱。

define (base) ^ (index) recursive
if <(index) = [1]>
  add (base) to [stack v]
else
  (base) ^ ((index) - (1)) recursive // adds the previous item to the stack
  add ((base) * (item (last v) of [stack v])) to [stack v]
  delete ((length of [stack v]) - (1)) of [stack v] // clean up

然后可以使用与我在other answer中解释的基本相同的方法访问它:

when gf clicked
(4) ^ (3) recursive // the stack block
say (join [4 ^ 3 = ] (item (last v) of [stack v])) // get the item from the end of the stack
delete [last v] of [stack v] // optional, if you want to clean up

See this in rendered ScratchBlocks.