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!

%%html

<div>
  <h3>Program Output</h3>
  <button id="onClickPH1"><a>Click to Roll Die</a></button>
  <p id="popcornHack1Output">Results will appear here:</p>
</div>

<script>
  (() => {
    class Dice { // What should the name of the class be?
      constructor(sides) { // Constructor to initialize the number of sides
        this.sides = sides; // Number of sides on the dice
      }

      roll() { // What should the name of the method be?
        return Math.floor(Math.random() * this.sides) + 1; // Rolls the dice and returns a number between 1 and the number of sides
      }
    }

    // Test the Dice class:
    // INSTANTIATE A NEW DICE OBJECT WITH A NUMBER OF SIDES
    const myDice = new Dice(6);

    let result;

    for (let i=0; i<5; i++){
      result = myDice.roll();
      console.log(result);
      output.innerText += "\n" + result;
    }

    // CALL THE ROLL METHOD A FEW TIMES AND PRINT THE RESULTS
    const output = document.getElementById("popcornHack1Output");

    const button = document.getElementById("onClickPH1");
    button.addEventListener("click", () => {
      result = myDice.roll();
      console.log(result);
      output.innerText += "\n" + result;
    });

  })();
</script>

Program Output

Results will appear here:

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!

%%html

<!-- i locked in on this -->
<!-- extra credit por favor -->

<!-- Also Pranay hates me now -->

<div>
  <h3>Program Output</h3>

  <button id="feedButton">Feed Pranay</button>
  <button id="playButton">Play with Pranay</button>
  <button id="showButton">Show Pranay's Status</button>

  <div id="outputPH2">Your results will appear here.</div>



</div>

<script>

(() => {

  const output = document.getElementById("outputPH2");

  class Pet {
    constructor(name, favoriteSport) {
      this.name = name;
      this.hunger = 90;   // you can change these values
      this.energy = 67;
      this.happiness = 0;
      this.favoriteSport = favoriteSport;
      // attributes all cap at 0 to 100
    }

    // TODO: Write at least 2 methods here
    //Example:
    feed() {
      this.hunger -= 5;
      if (this.hunger < 0){ this.hunger = 0; }

      this.energy += 5;
      if (this.energy > 100){ this.energy = 100; }

      this.happiness += 5;
      if (this.energy > 100){ this.happiness = 100; }

      console.log("Om nom nom, " + this.name +" ate food");
      output.innerText += "\n" + "Om nom nom, " + this.name +" ate food";
    }

    play() {
      this.energy -= 5;
      if (this.energy < 0){ this.energy = 0; }

      this.hunger += 5;
      if (this.energy > 100){ this.hunger = 100; }

      this.happiness += 5;
      if (this.happiness > 100){ this.happiness = 100; }

      console.log("Your pet " + this.name + " played " + this.favoriteSport);
      output.innerText += "\n" + "Your pet " + this.name + " played " + this.favoriteSport;
    }

    showStatus() {
      console.log(this.name.toUpperCase() + ": ");
      console.log("Energy: " + this.energy);
      console.log("Happiness: " + this.happiness);
      console.log("Hunger: " + this.hunger);
      console.log("Favorite Sport: " + this.favoriteSport + "\n");

      output.innerText += "\n\n" + this.name.toUpperCase() + ": "
      output.innerText += "\n" + "Energy: " + this.energy;
      output.innerText += "\n" + "Happiness: " + this.happiness;
      output.innerText += "\n" + "Hunger: " + this.hunger;
      output.innerText += "\n" +"Favorite Sport: " + this.favoriteSport + "\n";
    }
  }

  const myPet = new Pet("Pranay Kamath", "cricket"); // give your pet a name

  // Test your methods below:
  myPet.feed();
  myPet.play();
  myPet.showStatus();


  console.log("--- PRESS THE BUTTONS TO INTERACT WITH PRANAY ---");
  output.innerText += "\n" + "--- PRESS THE BUTTONS TO INTERACT WITH PRANAY ---";

  const feedButton = document.getElementById("feedButton");
  const playButton = document.getElementById("playButton");
  const showButton = document.getElementById("showButton");

  feedButton.addEventListener("click", () => {
    myPet.feed();
  });

  playButton.addEventListener("click", () => {
    myPet.play();
  });

  showButton.addEventListener("click", () => {
    myPet.showStatus();
  });


})();

</script>

Program Output

Your results will appear here.

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.
%%html

<div>
  <h3>Program Output</h3>
  <p id="hwOutput">Results will appear here:</p>
</div>

<script>
  (() => {

    const output = document.getElementById("hwOutput");

    function writeOutput(message) {
        output.innerText += "\n" + message;
        console.log(message);
    }

    class Person {
        constructor(name, age){
            this.name = name;
            this.age = age;
        }

        showProperties(){
            writeOutput("Name: " + this.name + ", age: " + this.age);
        }

        greet(){
            writeOutput("Hello, I am " + this.name + " and I am " + this.age + " years old");
        }
    }

    // problems 3-5

    class Book {
        constructor(title, author, pageCount) {
            this.title = title;
            this.author = author;
            this.pageCount = pageCount;
            this.pagesRead = 0;
        }

        read(pages){
            this.pagesRead += pages;
            if (this.pagesRead > this.pageCount){
                this.pagesRead = this.pageCount;
                writeOutput("You finished the book!");
            }
            writeOutput(`You read ${this.pagesRead}/${this.pageCount} pages total.`);
        }

        isLongBook(){
            return (this.pageCount > 300);
        }
    }

    // problems 6-9
    class Car {
        // make, model, fuelRemaining
        constructor(make, model, fuelCapacity, mpg) {
            this.make = make;
            this.model = model;
            this.fuelCapacity = fuelCapacity; // in gallons
            this.remainingFuel = this.fuelCapacity;
            this.milesPerGallon = mpg;
        }
        
        getRange(){
            return this.remainingFuel * this.milesPerGallon;
        }

        drive(distance){
            if (distance > this.getRange()){
                writeOutput("You don't have enough fuel to do that.");
            } else {
                const fuelUsed = distance / this.milesPerGallon;
                this.remainingFuel -= fuelUsed;
                this.remainingFuel = Number(this.remainingFuel.toFixed(2));
                writeOutput(`You drove ${distance} miles, there are ${this.remainingFuel.toFixed(2)} gallons of gas left.`);

            }
        }

        refuel(amtGals){
            if (this.remainingFuel == this.fuelCapacity){
                writeOutput("Your car is already full of gas!");
            } else {
                this.remainingFuel += amtGals;
                if (this.remainingFuel > this.fuelCapacity){
                    this.remainingFuel = this.fuelCapacity;
                }
                writeOutput(`You filled up your car,  it now has ${this.remainingFuel} gals of gas left.`);
            }
        }

        carStatus(){
            writeOutput(this.make+" " + this.model + " information: ");
            writeOutput(`${this.remainingFuel}/${this.fuelCapacity} gallons of gas remaining (${this.getRange()} miles)`);
        }

        static info(){
            writeOutput("Cars are vehicles.");
        }
    }

    // problem 8
    class ElectricCar extends Car {
        constructor(make, model, batteryCapacity) {
            super(make, model, null, null); // cuz they dont need fuel

            this.batteryCapacity = batteryCapacity; // in kwh
            this.remainingBattery = this.batteryCapacity;
        }

        charge(amount) {
            this.remainingBattery += amount;
            if (this.remainingBattery > this.batteryCapacity) {
                this.remainingBattery = this.batteryCapacity;
            }
            writeOutput(`${this.make} ${this.model} charged, battery level = ${this.remainingBattery}/${this.batteryCapacity} KWH.`);
        }

        batteryStatus() {
            writeOutput(`${this.make} ${this.model} battery: ${this.remainingBattery}/${this.batteryCapacity} kWh.`);
        }

        refuel() {
            writeOutput("Electric cars don't use fuel lol");
        }

        // Change to use battery instead of fuel
        drive(distance) {
            if (distance > this.getRange()) {
                writeOutput("You don't have enough battery to drive that far.");
            } else {
                const energyUsed = distance / this.milesPerKWh;
                this.batteryCapacity -= energyUsed;
                this.batteryCapacity = Number(this.batteryCapacity.toFixed(2));
                writeOutput(`You drove ${distance} miles. Battery left: ${this.batteryCapacity.toFixed(2)} kWh.`);
            }
        }
    }

    function myRoutine() {

        const bob = new Person("Bob", 67);
        bob.showProperties();
        bob.greet();

        writeOutput("\n---\n");

        const myBook = new Book("1984", "George Orwell", 320);
        writeOutput(myBook.title + " by " + myBook.author + " has " + myBook.pageCount + " pages.");
        myBook.read(10);
        writeOutput(`Is a long book: ${myBook.isLongBook()}`);

        writeOutput("\n---\n");

        const ferrari = new Car("Ferrari", "LaFerrari", 22.5, 14);
        ferrari.carStatus();
        ferrari.drive(100);
        ferrari.drive(999999999);
        ferrari.carStatus();
        ferrari.refuel(ferrari.fuelCapacity - ferrari.remainingFuel);
        ferrari.carStatus();
        Car.info();

        writeOutput("\n---\n");
        const tesla = new ElectricCar("Tesla", "Model S", 100, 3);
        tesla.charge(50);
        tesla.batteryStatus();
        tesla.drive(120);
        tesla.batteryStatus();
        tesla.refuel();
    }

    myRoutine();

  })();
</script>

Program Output

Results will appear here: