06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Algorithms 177<br />

With the above logic worked out, we can now move the timer in<strong>to</strong> a class. Let’s think about what data is<br />

involved in the timer. A timer must know the time at which it started ( savedTime) and how long it needs<br />

<strong>to</strong> run ( <strong>to</strong>talTime ).<br />

Data:<br />

• savedTime<br />

• <strong>to</strong>talTime<br />

Th e timer must also be able <strong>to</strong> start as well as check and see if it is fi nished .<br />

Functions:<br />

• start( )<br />

• isFinished( ) —returns true or false<br />

Taking the code from the non-object-oriented example and building it out with the above structure, we<br />

have the code shown in Example 10-5.<br />

Example 10-5: Object-oriented timer<br />

Timer timer;<br />

void setup() {<br />

size(200,200);<br />

background(0);<br />

timer = new Timer(5000);<br />

timer.start();<br />

}<br />

void draw() {<br />

if (timer.isFinished()) {<br />

background(random(255));<br />

timer.start();<br />

}<br />

}<br />

class Timer {<br />

int savedTime; // When Timer started<br />

int <strong>to</strong>talTime; // How long Timer should last<br />

Timer(int tempTotalTime) {<br />

<strong>to</strong>talTime = tempTotalTime;<br />

}<br />

// Starting the timer<br />

void start() {<br />

savedTime = millis();<br />

}<br />

boolean isFinished() {<br />

// Check how much time has passed<br />

int passedTime = millis()- savedTime;<br />

if (passedTime > <strong>to</strong>talTime) {<br />

return true;<br />

} else {<br />

return false;<br />

}<br />

}<br />

}<br />

When the timer starts it s<strong>to</strong>res the current time in<br />

milliseconds.<br />

The function isFinished() returns<br />

true if 5,000 ms have passed. The<br />

work of the timer is farmed out <strong>to</strong><br />

this method.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!