Classes and Methods

Popcorn Hack 1 - Dice Roller

Instructions: Finish the code in the cell below (fill in underlines and add lines of code) so it works as described:

  • Create a class called Dice that:
    • Has a property for the number of sides.
    • Has a method roll() that returns a random number between 1 and the number of sides.

At the bottom, test your game by making a DiceGame object and calling roll() a few times.

The code is currently NOT functional. When you have completed this popcorn hack, the code should work. Have fun!

%% javascript

// Define the Dice class
class Dice {
  // The constructor runs when a new Dice is created
  constructor(sides) {
    this.sides = sides;
  }

  // Define a method named 'roll' (not 'Dice')
  roll() {
    return Math.floor(Math.random() * this.sides) + 1;
  }
}

// Test the Dice class:

// Create a new Dice object with 6 sides
let myDice = new Dice(6);

// Roll the dice a few times
console.log(myDice.roll());
console.log(myDice.roll());
console.log(myDice.roll());

<IPython.core.display.Javascript object>

Popcorn Hack 2 - Pet Simulator

This hack is a bit more complicated than the first. Points will be awarded based on effort and completion.

Analyze the block of code below. Then, complete the following instructions:

1) Create a simple Pet class by filling in the _____.

2) Add at least 2 properties (like hunger, energy, or happiness). EX: Stats decrease over time.

3) Add at least two functioning methods (such as feed, play, or sleep) EX: Buttons increase stats.

4) Give your pet a name and print their current properties.

5) Bonus: Add a “status” method to print all your pet’s stats.

The code is currently NOT functional. When you have completed this popcorn hack, the code should work. Have fun!

%% javascript

class pet {
  constructor(name) {
    this.name = name;
    this.hunger = 5;   // you can change these values
    this.energy = 5;
    this.happiness = 5;
  }

  // TODO: Write at least 2 methods here
  //Example:
  feed() {
    this.hunger -= 2; // allow user to feed pet (add button to call this method)
    this.energy += 2; // increase energy, decrease hunger, increase happiness
    this.happiness += 1;
    console.log(`${this.name} has been fed!`);
    this.status();
  }

  play() {
    this.energy -= 2; // allow user to play w/ pet by clicking a button to call this method
    this.hunger += 1; // decrease energy, increase hunger, increase happiness
    this.happiness += 2;
    console.log(`${this.name} has been played with!`);
    this.status();
  }

  const myPet = new pet("Rocket"); // Dont judge the name
console.log(myPet); // print the properties of your pet to console
output.innerText = `${myPet.name}'s Stats → Hunger: ${myPet.hunger}, Energy: ${myPet.energy}, Happiness: ${myPet.happiness}`;

// Test your methods below:
myPet.feed();
myPet.play();
<IPython.core.display.Javascript object>

Homework

Complete the following questions in the next code block.

1) Create a class Person with properties ‘name’ and ‘age’. Print their properties.

2) Add a method greet() to your Person class that prints a greeting using the person’s name.

3) Create a class Book with properties ‘title’, ‘author’, and ‘pages’. Instantiate a book and print its properties.

4) Add a method read(pages) to your Book class that increments a pagesRead property and prints a message.

5) Add a method isLongBook() that returns true if pages > 300, otherwise false. Print the result for your book.

6) Create a class Car with properties ‘make’, ‘model’, and ‘fuel’. Add methods drive(distance) and refuel(amount). Print messages in each method.

7) Add a static method info() to your Car class that prints ‘Cars are vehicles.’

8) Create a class ElectricCar that extends Car. Add a property ‘battery’ and a method charge(amount) that increases battery. Print battery level after charging.

10) Create a routine that combines your objects: drive a Car, charge an ElectricCar, read pages from a Book, and call greet() on Person. Print outputs for each action.

11) Extra Credit: Submit the original OOP Breakout Game Code (found on OpenCS) after making the following edits:

  • Add another feature to the game: Add a method so that the ball must collide with some bricks twice for a brick to break completely.
  • Edit a method in the ball class to increase/decrease the speed of the ball: Please add a COMMENT on the game code that specifies which line you edited.
%% javascript

class Person {
    constructor(name, age, city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
    // Way to Greet the Person
    greet() {
        return `My name is ${this.name}, I am ${this.age} years old and I live in ${this.city}.`;
    }
    // The Person
    const person1 = new Person("Aryan", 14, "California");
console.log(person1);
person1.greet();

//Book class
class Book {
    constructor(title, author, pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
        this.pagesRead = 0; // track progress
    }

    read(pages) {   // method to read pages
        this.pagesRead += pages;
        if (this.pagesRead > this.pages) {
            this.pagesRead = this.pages; // can't read more than total pages
        }
        console.log(`You have read ${this.pagesRead} out of ${this.pages} pages of "${this.title}".`);
    }

    isLongBook() {  // method to check if book is long
        return this.pages > 300;
    }
}

// Create the/ aq Book and Print Details
const myBook = new Book("The Great Adventure", "John Writer", 350);
console.log(myBook);
myBook.read(50);
console.log(`Is "${myBook.title}" a long book?`, myBook.isLongBook());


// Create a Car Class
class Car {
    constructor(make, model, year) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.fuelLevel = 100; // fuel level percentage
    }

    drive(miles) { // method to drive the car
        const fuelConsumed = miles / 10; // assume 10 miles per unit of fuel
        this.fuelLevel -= fuelConsumed;
        if (this.fuelLevel < 0) {
            this.fuelLevel = 0; // can't have negative fuel
            console.log("The car is out of fuel!");
        } else {
            console.log(`You drove ${miles} miles. Fuel level is now ${this.fuelLevel}%.`);
        }
    }

    refuel(amount) { // method to refuel the car
        this.fuelLevel += amount;
        if (this.fuelLevel > 100) {
            this.fuelLevel = 100; // can't exceed 100%
        }
        console.log(`The car has been refueled. Fuel level is now ${this.fuelLevel}%.`);
    }
}

// Create a Car Object and Test Methods
const myCar = new Car("Toyota", "Corolla", 2020);
console.log(myCar);
myCar.drive(50);
myCar.refuel(30);
myCar.drive(300);

%% javascript
document.getElementById("output").innerText = "Homework Output:\n";
<IPython.core.display.Javascript object>