2018-09-11 18:02:40 +02:00
# Turtle Square
2018-09-11 19:38:58 +02:00
## Introduction @unplugged
2018-09-11 18:02:40 +02:00
2018-10-24 21:02:31 +02:00
Imagine that there's a virtual turtle, as small as an LED, that you can control with commands. In this tutorial, you will learn to use the turtle and draw a square.
2018-09-11 18:02:40 +02:00
2018-09-11 19:38:58 +02:00
## Moving the turtle @fullscreen
2018-09-11 18:02:40 +02:00
2018-10-24 21:02:31 +02:00
The turtle starts in the center of the screen heading upward. Place a ``||turtle:forward||`` block to make it move up.
2018-09-11 18:02:40 +02:00
2018-09-11 19:38:58 +02:00
```blocks
turtle.forward(1)
```
2018-09-11 18:02:40 +02:00
2018-09-11 19:38:58 +02:00
## Turning and moving @fullscreen
2018-09-11 18:02:40 +02:00
2018-09-11 19:38:58 +02:00
Place a ``||turtle:turnRight||`` to turn the turtle and place another ``||turtle:forward||`` block to make it move again.
2018-09-11 18:02:40 +02:00
```blocks
2018-09-11 19:38:58 +02:00
turtle.forward(1)
2018-09-11 18:02:40 +02:00
turtle.turnRight()
2018-09-11 19:38:58 +02:00
turtle.forward(1)
2018-09-11 18:02:40 +02:00
```
## Drawing a square
2018-10-24 21:02:31 +02:00
If you add enough ``||turtle:turnRight||`` and ``||turtle:forward||`` blocks, the turtle will eventually draw a square.
2018-09-17 23:19:03 +02:00
2018-10-24 21:02:31 +02:00
You can move the blocks into a ``||input:on button pressed||`` to easily run the code again.
2018-09-11 18:02:40 +02:00
```blocks
2018-09-11 19:38:58 +02:00
input.onButtonPressed(Button.A, function() {
turtle.forward(1)
turtle.turnRight()
turtle.forward(1)
turtle.turnRight()
turtle.forward(1)
2018-09-11 18:02:40 +02:00
turtle.turnRight()
2018-09-11 19:38:58 +02:00
turtle.forward(1)
turtle.turnRight()
})
```
2018-10-24 21:02:31 +02:00
## "for" is for repetition
2018-09-11 19:38:58 +02:00
2018-10-24 21:02:31 +02:00
Did you notice the pattern of repeated blocks needed to draw a square? Try using a ``for`` loop to achieve the same effect.
2018-09-11 19:38:58 +02:00
```blocks
input.onButtonPressed(Button.A, function() {
for(let i = 0; i < =4; ++i) {
turtle.forward(1)
turtle.turnRight()
}
})
```
## Leaving a trail
2018-10-24 21:02:31 +02:00
The turtle holds a **pen** that can turn on LEDs. If you add the ``||turtle:pen||`` block, it will leave a trail as the turtle moves.
2018-09-11 19:38:58 +02:00
```blocks
input.onButtonPressed(Button.A, function() {
turtle.pen(TurtlePenMode.Down)
for(let i = 0; i < =4; ++i) {
turtle.forward(1)
turtle.turnRight()
}
})
2018-09-11 18:02:40 +02:00
```
```package
2018-10-16 00:32:09 +02:00
microturtle=github:Microsoft/pxt-microturtle#v0.0.9
2018-09-11 18:02:40 +02:00
```