Week 6 - Timers and Classes and Objects

Today’s Schedule

on Zoom

  • Check-in/Review
    • functions
  • Midterm info
  • Review simple AI homework
  • Timers with millis()
  • Classes and Objects
  • Frogger

Midterm Exam

Take-home exam on Oct 17. Relax! We will have a study sheet. Your exam and project are together worth 15%.

Midterm project

Midterm project is due on Oct 24 (3 weeks).

Timer functionality using millis()

Let’s build a timer

We need two variables:

  • a variable to hold the present time
  • a variable that stands for the amount of time to wait until alarm goes off

Processing has the millis() command which always returns the number of milliseconds since our program began. 1000 milliseconds equals 1 second.

  • How many milliseconds in a 30 second timer?
  • How many milliseconds in an hour?
//Basic timer
//timer goes off after 3 seconds
int wait = 3000; //wait 3 seconds (3000 millis)

void setup(){
  size(200,200);
}

void draw(){
  if(millis() > wait){
    println("ALARM!"); //will keep printing in the loop
  }
}

To answer: why does it repeatedly print “ALARM” after 3 seconds?

How would we have a timer go off every X seconds?

//Basic timer
//timer goes off every 5 seconds
int wait = 5000; //wait 5 seconds (5000 millis)

void setup(){
  size(200,200);
}

void draw(){
  //check the difference between now and the previously stored time is greater than the wait interval
  if(millis() > wait){
    println("ALARM!");
    wait = wait + 5000; //Add 5 more seconds to the waiting time
  }
}

Classes and Objects

Processing (and Java) are Object-oriented programming.

Objects have properties.

I am a person. I have hair color, age, name, height, for example.

You are a person. You have your own hair color, age, name, height.

We have the same variables names. But my hair color, age, name, height are different from yours, and different from other people’s.

Objects have their own instances of variables and functions (methods)

To learn about objects, we are going to create Frogger

What is a class?

In a programming language, a class is a defined code template that is used to create objects. We say that classes encapsulate objects. In other words, they enclose all of the variables and functions needed for each object.

  • They store functions and variables together
  • A class is a template - a cookie-cutter
  • They are used to stamp out individual Objects
  • When we stamp out or create an object using the Class/cookie cutter we are said to be instantiating an object. Each object is an instance of the class.
  • Each time you use the class to create a new object instance, it will have its own variables and functions assigned to it

Example:

My Class name is People

I have an instance of People with the variable name Carl. Carl’s first_last is Carl Winslow. Carl’s height is 68 (we may know this to be inches). I have another instance of People with the variable name Steve. Steve’s first_last is Steve_Urkel. Steve’s height is 71. Both have the same associated attributes (which we can think of as associated variables) but they each have their OWN that are independent from each other.

How to write a class

  • example taken from Daniel Shiffman, Learning Processing
void setup(){

}

void draw(){

}

//note that by convention we capitalize a class name
class Car {

}

Let’s create a class

We create a new object with the new operator.

main structure of our program:

Car myCar; //declares an object myCar of type Car

void setup(){
  myCar = new Car(); //this is the object initialization.
}

void draw(){
    background(255);
    myCar.move();
    myCar.display();
}

By convention, we place our classes in their own tab in Processing. Click the New Tab, and name the file with the class name. When you save your Processing program it will save your code from all of the tabs.

Keep in mind that when you are looking at one tab and hit the compile/run button it will also compile and run the code from your other tabs even though you can’t see them all open simultaneously.

It is recommended to keep your global variables, setup, draw on the first tab, and generally our user-defined functions. Place your Class definitions on other tabs.

Let’s create our Car class. Open a new tab. Now add:

class Car {

  color c;
  float xpos;
  float ypos;
  float xspeed;

  Car() {
    c = color(255);
    xpos = width/2;
    ypos = height/2;
    xspeed = 1;
  }

  void display() {
    //The car is just a rectangle
    rectMode(CENTER);
    fill(c);
    rect(xpos, ypos, 20, 10);
  }

  void move(){
    xpos = xpos + xspeed;
    if (xpos > width){
      xpos = 0;
    }
  }
}

Objects with arguments

When you pass in a variable when you call a function, you are technically passing in the value of the variable at that moment.

Objects work differently. When you supply an argument to an object created with a class, you create a temporary reference to stand in for the variable you will be passing in.

from Learning Processing

Frog f; //declares an object f of type Frog

void setup(){
    f = new Frog(100); //100 goes into tempTongueLength
}

class Frog{
  int tongueLength; //creates an instance variable

  Frog (int tempTongueLength){ //temporary local variable
      tongueLength = tempTongueLength; //assigns the value to tongueLength
  }
}

Question: When do you use a class/object versus when do you use a function?

Homework Programming

Build off the work we did in class to finish your Frogger-derived game. You can make your game more or less difficult depending on the speed. Consider the speed of the frog, and of the cars. It is okay to deviate from the classic Frogger gameplay and make your own version (in fact, it’s encouraged). Use functions, classes and objects. Pay attention to functionality. Make the game a challenge, but make it playable. Use variables.

  1. Make a frog class and a car class.
  2. Use the arrow keys to control the frog.
  3. check if the frog has hit a car. If so, move the frog back to the start at the bottom of the screen. Hint: Consider how we checked whether the pong ball was on top of the rectangle. Use that knowledge to check whether the frog has hit a car. Add a checkForCollision() function inside your Car class and use on each car instance.
  4. Add a score and lives. Start with 3 lives. If the frog gets hit 3 times, end the game. (background black and noLoop() ). Each time the frog gets to the top, add 1 to the score and start the frog over again from the bottom. When you die, print out the final score with println().

Make sure you break your code into modular functions. Add comments so that I (and you) can read and understand your code.

  • Optional challenge: Add a countdown timer so that you have limited time to get to the other side. Each time you successfully cross (or get hit by a car and start over), reset the timer.
  • Optional challenge for CS/M and advanced students: Add a gameplay dynamic so that the game gets harder each time you reach the other side.

Resources

The Coding Train videos on Chapter 8: Objects

Reading

  1. Re-Read Chapter 8 on Objects in Learning Processing
  2. Read Chapter 9 on Arrays in prep for next week

Midterm Tamagotchi

Tamagotchi

We are a little over a third of the way through the semester and have come far in our programming knowledge. We have covered variables and types, conditionals, loops, functions, translations, interaction through keypresses and the mouse, classes and objects. Next week we will add in arrays to complete the foundations. Taking the totality of what we’ve learned so far our midterm project is to code a Tamagotchi, type of digital pet such as a Furby or artificial human companions.

Furby

Part A due next week:

  1. Sketch out what your Tamagotchi creature looks like in its resting state. Note that your digital pet could be an animal, robot, plant, etc.
  2. Write down the various states your Tamagotchi can take. For example: resting (neutral), sleeping, eating, crying, playing a game, talking. Include at least 3 states and no more than 5.
  3. Draw a flow chart consisting of a finite state machine diagram showing how it progresses between states. For example, bored (fed) -> happy. bored (not fed) -> crying. Indicate what causes it to change from one state to another. This could be a timer or a trigger (“petting” a dog by clicking on it, etc).

dog finite state machine

animal finite state machine

Pacman finite state machine

Weeks ahead: Part B will be to create your creature’s Class in code. Part C will be to implement timers and interactivity to build the state machine.