Note: We will take breaks at least once an hour
Several weeks ago we built Frogger in class. We created a Car class and then built a number of car objects (car0, car1, car2, etc). What do these objects have in common?
This is a perfect use case for an array. Especially if we want to make a large number of cars.
Let’s re-use our car class:
class Car {
float x;
float y;
float xspeed;
color c;
Car(float tempX, float tempY, float tempXspeed, color tempC){
c = tempC;
x = tempX;
y = tempY;
xspeed = tempXspeed;
}
void display(){
rectMode(CENTER);
stroke(0);
fill(c);
rect(x, y, 20, 10);
}
void move(){
x = x + xspeed;
if (x > width){
x = 0;
}
if (x < 0){
x = width;
}
}
}
Let’s say we have 2 cars.
Our main code:
Car car0, car1;
void setup(){
size(500,500);
car0 = new Car(100,150,1,color(100,0,100));
car1 = new Car(300,230,2,color(220,0,120));
}
void draw(){
background(255);
car0.display();
car0.move();
car1.display();
car1.move();
}
What happens if we have more than 2 cars. What if we have 10 cars? 30 cars?
It would be a lot easier if we didn’t have type in all of the cars individually.
Car[] cars = new Car[20]; //an array of 20 cars
void setup(){
size(500,500);
for (int i = 0; i < cars.length; i++){
cars[i] = new Car(random(width),random(height),random(2),color(random(255)));
}
}
void draw(){
for (int i = 0; i < cars.length; i++){
cars[i].display();
cars[i].move();
}
}
Processing comes with a Debugger.
What’s a bug?
an error, flaw, failure or fault in a computer program or system that causes it to produce an incorrect or unexpected result, or to behave in unintended ways. Wikipedia
Bugs cause disasters:
A few weeks ago we looked at diagrams of finite state machines.
Today, we will code one.
At its core, the finite state machine are a series of functions with different states. You can transition between these states. And you can never be in more than one state at a time.
void draw(){
if (state == "sleeping"){
sleeping();
} else if (state == "laughing"){
laughing();
} else if (state == "eating"){
eating();
} else {
sitting();
}
}
String state = "sleeping";
void setup(){
}
void draw(){
if (state == "sleeping"){
sleeping();
} else if (state == "eating") {
eating();
} else {
sitting();
}
}
void sleeping(){
println("It's sleeping");
if (mousePressed){
state = "sitting";
}
}
void sitting(){
println("It's sitting");
if (mousePressed){
state = "eating";
}
}
void eating(){
println("It's eating");
if (mousePressed){
state = "sitting";
}
}
Now we add in:
Prototype of virtual pet due.
Your prototype must include:
Grading Rubric for final of virtual pet project: