使用循环#

Using Loops

This tutorial walks you through using the repeat block to drive your robot in a square in VEXcode IQ (1st gen). By the end, you’ll have a project that repeats the same two blocks four times to complete the square.

If you want your robot to repeat the same action multiple times, like driving in a square, you could keep duplicating the same blocks over and over until they move in the pattern of a square. A simpler way, however, is to use the repeat block within the Logic - Control category.

  1. Attach a drive for block and a turn for block below the when started block.

One side of the square, driving forward then turning right.#
当开始
驱动 [向前 v] (200) [毫米 v] ▶
[右 v] 转 (90) 度 ▶
  1. Attach a repeat block below the when started block.

The repeat block, attached above the drive for and turn for blocks.#
当开始
重复 (10)
结束
驱动 [向前 v] (200) [毫米 v] ▶
[右 v] 转 (90) 度 ▶
  1. Drag the drive for and turn for blocks inside the repeat block.

The drive for and turn for blocks, now inside the repeat block.#
当开始
重复 (10)
驱动 [向前 v] (200) [毫米 v] ▶
[右 v] 转 (90) 度 ▶
结束
  1. Select the repeat number and change it to 4, so the blocks inside run once for each side of the square.

Screenshot of the repeat block's number highlighted, set to 4.
  1. Make sure your robot is connected to VEXcode, then select Download to download the project to the Brain.

Screenshot of the VEXcode IQ (1st gen) toolbar with the Download button highlighted.
  1. Select Run to run the project. The robot will drive in a square.

Screenshot of the VEXcode IQ (1st gen) toolbar with the Run button highlighted.

You can also repeat a sequence of actions forever, using the forever block instead of repeat.

The forever block.#
永久循环
结束

To break out of a loop, use the break block within a loop, to make the code exit the looping block immediately.

The break block.#
退出循环