3

My goal is to build a 5x5 grid of images. In the following code, row, col and rowcol were created as variables local to the sprite, and newcol, newrow and cats are global. (By the way, is it possible to tell which variables are local and which are global? It's easy to forget or make mistakes.)

code

The result is a 5x1 grid only, as seen here.

results

I am unclear as to the order of execution of these statements. Does when I start as a clone get called before or after add_cat gets called the second time? My tentative conclusion is that it gets called afterwards, yet the clone's global variables seem to contain their values from beforehand instead.

When I attempted to debug it with ask and say and wait commands, the results varied wildly. Adding such pauses in some places fixed the problem completely, resulting in a 5x5 grid. In other places, they caused a 1x5 grid.

The main question is: How to fix this so that it produces a 5x5 grid?

4

1 回答 1

5

解释

不幸的是,Scratch 中的执行顺序有点奇怪。每当您编辑脚本(通过添加或删除块、编辑输入或将整个脚本拖到编辑器中的新位置)时,它都会被放置在列表的底部(因此它最后运行)。

测试这一点的一个好方法是使用以下脚本创建一个空白项目:
两个相似的脚本

当您单击绿色标志时,精灵会“脚本一”或“脚本二”,具体取决于哪个先运行。尝试单击并拖动其中一个when green flag clicked块。下次您单击绿色标志时,精灵会说出与您刚刚拖动的脚本相对应的任何消息。

这种疯狂的顺序会使执行变得难以置信,尤其是在使用克隆时。

解决方案

唯一真正的解决方案是编写内置有明确执行顺序的代码(而不是依赖于编辑器的突发奇想)。对于更简单的脚本,这通常意味着利用broadcast and wait块以必要的顺序运行特定事件。

对于您的特定项目,我看到两个主要解决方案:

程序解决方案 这是最直接的脚本,它可能是我会选择使用的:(并且都是sprite-only 变量) 因为克隆在创建时继承了所有 sprite-only 变量值,所以每个克隆都将保证具有创建时正确的行和列。
程序解决方案
rowcol

递归解决方案 这个解决方案比第一个更难理解,所以我可能会避免它,除非你只是在寻找新奇:
递归解

于 2017-03-24T01:37:08.483 回答