Array Destructuring!
Goals:
- Assign variable names to elements in arrays of known length using a technique called array destructuring
- Learn how to ensure that program statements get evaluated in the desired sequence by manipulating the animation queue with calls to
await done defer()
Coding Snippets:
await done defer()
must be called before calls to functions that return information about the current state of animation.sizexy
returns the dimensions of the visible screen as an array of two whole numbers.getxy
returns a sprite's coordinates as an array of two integers.see
prints output to the test panel console. It is useful for debugging code.
Math and Computer Concepts:
- When a program is run, Pencil Code executes all statements related to animation at once, creating schedules of tasks to be carried out in the future. Pencil Code uses these schedules, or animation queues, to display the animated results after the program finishes.
- Functions that are not directly related to animation, such as
getxy
andsee
, are also executed before animation begins. As a result, such functions may appear to provide incorrect results. The actual problem is that they are executing at the wrong time.
- To get functions that are not placed in the queue to execute at the right time, precede them with the statement
await done defer()
. This cryptic line of code forces Pencil Code to wait until all animations up to that point in the program have been carried out, before executing statements coming after it.
Activities:
Save each of the following in a folder called Destructuring.
- Create two programs that completely fill in the visible screen with a color of your choice, bounded by a black edge. Base the dimensions on the output from
sizexy
. In the first program, SlideFiller, the only movement function you can use isslide
. In the second variant, MovetoFiller, come up with an algorithm that accomplishes the same goal but this time using onlymoveto
for sprite movement. FramedImage: Create an image sprite of your choice. Write a script that creates a frame around the image that fits perfectly inside the screen. Write your code using variables, so that you can easily adjust the thickness of your frame.
- A feature common to regular stars is that their points lie along the edge of a circle. This fact suggests an alternative algorithm for drawing stars with an odd numbers of points. Code an OddStarMaker program that uses two turtles,
t1
andt2
. Instructt1
to move around the edge of a circle, according to the statementt1.rt (360 - 360/points)/2, radius
. Havet2
then draw a straight line to wheret1
ended up.