OOP Studio Ages 9-15
State Builder
Students add multiple methods that change and report an object's state.
Build energy actions.
Example code
class RobotPet {
constructor(name) {
this.name = name;
this.energy = 2;
}
rest() {
this.energy += 2;
say(this.name + " rested. Energy: " + this.energy);
}
play() {
this.energy -= 1;
say(this.name + " played. Energy: " + this.energy);
}
status() {
say(this.name + " has " + this.energy + " energy.");
}
}
let bolt = new RobotPet("Bolt");
bolt.status();
bolt.play();
bolt.rest();
Program result
- Run your code to see output.
Type real JavaScript, then run it.
State builder complete.
You added methods that change energy and report the object's current state.
Try State Challenge