什么是 Scratch 中的条件编程?
Scratch 是一种高级可视化编程语言工具,它通过内置程序基础的图表和块与用户进行交互。 Scratch 用于制作交互式程序,特别适合使用块式界面的孩子,以便他们可以轻松学习语言并且免费使用。在本文中,我们将了解坐标和条件。
坐标系
在 Scratch 中,坐标系用于在屏幕上定位精灵(如果是场景,则为演员),或者我们可以说坐标系是一个具有无限值的数学网格。它是一个二维笛卡尔坐标系,用于分配点/对象或提取对象/点的位置。
位置:坐标系有两个坐标,即X位置和Y位置来查找精灵在屏幕上的位置。这里,X 位置表示精灵的水平位置,Y 位置表示精灵的垂直位置。 X 位置的范围可以是 240 到 -240,其中 240 是舞台或屏幕的最右侧,-240 是最左侧,Y 位置的范围是 180 到 -180,其中 180 是最顶部,-180 是最底端。坐标可以写成 (X, Y)。例如,(3, 4) 是舞台上精灵的坐标。
将划痕的背景更改为 xy 网格。在屏幕右下角,点击“背景”选项,选择xy坐标系作为背景。
将会有许多从 Scratch 提供的背景列表,如下所示:
现在,选择“xy 网格”背景,您将观察到精灵的背景变为 xy 网格。这个 xy 网格给出了 x 和 y 坐标的最小值、最大值和中心值的准确概念。当精灵从一个地方移动到另一个地方时,相应的 x、y 坐标也会同时显示。这在上面的 gif 中有所描述。
通过使用运动块可以确定、设置和更改精灵的 X 位置和 Y 位置。以下是可以修改精灵坐标的方法。
从头开始的条件
条件语句具有条件,程序根据条件的真假值流动。它们位于控制编程块中,如下所示。
这里, if() then 和 if() then else 是条件块。
1. if() then 阻塞
它是一个控制块。此块适用于条件的值。如果条件为真,则执行该组代码,否则什么也不会发生。在这里,条件只检查一次,如果在脚本运行时将条件更改为 false,则脚本将继续运行,直到完成。就像Java、 Python等语言中的 if-else 语句一样。让我们通过做一个小项目来理解这个概念。让我们借助一个简单的项目来了解等待块的工作原理。在这个项目中,如果用户输入“a”,那么精灵必须滑行 1 秒。
程序:
Step 1: Click on event block and choose 1st control block denoting start of the program(drag it to center).
Step 2: Click on control block and drag if then block below the above step.
Step 3: Go to the sensing block and drag key space pressed and place it inside the condition of if-then block and change “space” to “a”
Step 4: Go to motion block and drag glide 1 sec to random position inside if-then block.
Step 5: Now, run the program.
下面是上述过程的实现。
2. if-then-else
它是一个控制块。此块是 if-then 值的扩展。如果条件为真,则执行一组行。如果条件为假,则执行 else 部分。让我们借助一个简单的项目来了解等待块的工作原理。在这个项目中,如果用户输入“a”,那么精灵必须滑行 1 秒,否则精灵必须说“你好”。
程序:
Step 1: Click on event block and choose 1st control block denoting the start of the program(drag it to center).
Step 2: Click on the control block and drag if then block below the above step.
Step 3: Go to the sensing block and drag key space pressed and place it inside the condition of if then block, change “space” to “a”
Step 4: Go to motion block and drag glide 1 sec to a random position, inside the if then block.
Step 5: Go to looks block and drag say hello block inside else part.
Step 6: Now run the program
下面是程序的实现: