Selection - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki
Last week we introduced the three programming concepts of sequence, selection, and iteration. We have introduced sequence and iteration, but we haven't yet covered selection.
Selection is a computer's ability to make decisions. It is the foundation of artificial intelligence. Sequence and iteration make computers great machines for automating tasks, but it is selection that makes them smart.
Selection is deciding whether to execute a portion of code or not. When we introduced syntax the example was to go to the store and pick up some milk. Selection would involve whether we should buy some milk. For example, we might buy some milk if we have run out, or if the current milk is beyond it's expiry, or if we are planning a large gathering.
The if statement
Most programming languages implement selection with the if statement.
Our animation example causes the ellipse to go off the right hand side of the canvas, what if we wanted it to stop at the end of the canvas?
One way to do this would be to only increment the x co-ordinate of the ellipse if the x co-ordinate was less than the width of the canvas. For example we could write the following:
if (x < windowWidth) {
x = x + 5;
}
The problem here is that x represents the centre of the ellipse. So we actually need to stop half the width of the ellipse before the end of the canvas, e.g.:
if (x < windowWidth - 25) {
x = x + 5;
}
Bouncing Ball
We can go a step further and change the direction of the ball once it hits the edge. To do this we need to store the direction in a separate variable and change it when we hit the edge:
var x = 50;
var direction = 5;
function draw() {
background(100);
ellipse(x, 100, 50, 50);
x = x + direction;
if (x > windowWidth - 25) {
direction = -5;
}
}
You can see an example here.
Note how our if statement changed. We now want to know if the x co-ordinate is greater than (not less than) the windowWidth less half the width of the ellipse.
Once the ball returns it now goes off the left edge of the canvas! We can use another if statement to make it bounce on the left edge:
if (x < 25) {
direction = 5;
}
This if statement reverts the direction forwards again.
It will now bounce forever!
Next: Mouse Interaction