OUCC

 
 
 

OUCC Tutorials

Blockly Movie Task

Example 3 - Why you should avoid loops in this module
Here is an example of a programming style that is not recommended. Can you work out what you think will happen before pressing Run?

It is important to remember that there is a clock ticking in the Movie module and the code you write is evaluated in every tick from the start. If your code includes loops there is a danger that they will not be fully evaluated in the time available and unexpected outcomes might result.

Try and answer the following questions yourself and then look at the answers.

Questions:
Q1. Why did the green circle fail to appear until frame 51 whereas it was always there when we used an if block in example 2?

Q2. Why is there a green circle shown from frame 51 until the end of the animation?

Q3. If using loops is not recommended, how can this animation be better achieved?

Answers:
A1. To answer this question lets consider what happens in frame 6. The while loop checks to see what the time block returns and, if it is less than 51, the code inside the loop is evaluated. As the time block returns 6 in this frame of the animation, the code inside the while block is evaluated and a red circle is drawn at the x-coordinate 6. The program flow then returns to the while loop test and, again, the test returns true because the time block still returns 6. Another red circle is drawn on top of the first. This continues to happen until the time available for this frame is over and the animation moves to frame 7. In frame 6 the while loop is never exited and so the green circle block is never reached. This happens for all frames below frame 51.

A2. At frame 51 the time block returns 51. This is greater than 50 and so the while block is skipped giving the chance for the green circle shape block to be evaluated and a green circle shown. This happens in all frames from 51 until the end of the animation.

A3. This is better achieved by using an if else block which is what was done in example 1.

<< Back

Movie Tutorial Start
Example 1 - Using an if else clause
Example 2 - Using just an if clause
Example 3 - Why you should avoid loops in this module

Tutorials index


[ tutorials | terms | privacy | info@oucc.uk ]


UKCT Challenges are proud to use The Cuttle Platform to host our challenges.
The Cuttle system can be used for maths and science competitions, entrance exams or employee exams.