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

<html>
<body>
  <h2>Popcorn Hack 1 Output</h2>
  <div id="output1"></div>

  <script>
  (() => {

    class Dice {
      constructor(sides) {
        this.sides = sides; 
      }

      roll() {
        return Math.floor(Math.random() * this.sides) + 1;
      }
    }

    let myDice = new Dice(6);

    var dice1Val = myDice.roll();
    var dice2Val = myDice.roll();
    var dice3Val = myDice.roll();

    document.getElementById("output1").innerText =
      "Dice Roll 1: " + dice1Val + "\n" +
      "Dice Roll 2: " + dice2Val + "\n" +
      "Dice Roll 3: " + dice3Val;

    console.log("Rolled Val1: " + dice1Val);
    console.log("Rolled Val2: " + dice2Val);
    console.log("Rolled Val3: " + dice3Val);

  })();
  </script>
</body>
</html>

Popcorn Hack 1 Output

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
<html>
<body>
  <h2>Popcorn Hack 2 - Pet Simulator</h2>
  <div id="petOutput"></div>

  <button id="feedBtn">Feed</button>
  <button id="playBtn">Play</button>
  <button id="sleepBtn">Sleep</button>

  <script>
  (() => {
    class Pet {
      constructor(name) {
        this.name = name;
        this.hunger = 1;      
        this.energy = 8;      
        this.happiness = 10;  
      }

      feed() {
        this.hunger = Math.max(0, this.hunger - 2);
        this.energy = Math.min(10, this.energy + 1);
        this.happiness = Math.min(10, this.happiness + 1);
        this.updateDisplay(`${this.name} enjoyed a snack! 🍗`);
      }

      play() {
        this.energy = Math.max(0, this.energy - 2);
        this.hunger = Math.min(10, this.hunger + 1);
        this.happiness = Math.min(10, this.happiness + 1);
        this.updateDisplay(`${this.name} had fun playing! 🎉`);
      }

      sleep() {
        this.energy = Math.min(10, this.energy + 3);
        this.hunger = Math.min(10, this.hunger + 1);
        this.updateDisplay(`${this.name} took a nap. 😴`);
      }

      updateDisplay(message) {
        document.getElementById("petOutput").innerText =
          message + "\n" +
          this.name + "'s Current Stats:\n" +
          "Hunger: " + this.hunger + "\n" +
          "Energy: " + this.energy + "\n" +
          "Happiness: " + this.happiness;
      }
    }

    const myPet = new Pet('Pranay');
    myPet.updateDisplay(`${myPet.name} is ready!`);

    document.getElementById('feedBtn').onclick = () => myPet.feed();
    document.getElementById('playBtn').onclick = () => myPet.play();
    document.getElementById('sleepBtn').onclick = () => myPet.sleep();

  })();
  </script>
</body>
</html>

Popcorn Hack 2 - Pet Simulator

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
<html>
<body>
  <h2>Homework - Classes & Methods</h2>
  <div id="hwOutput" style="white-space: pre-line; border:1px solid #ccc; padding:10px; margin:10px 0;"></div>

  <script>
  (() => {
    const output = document.getElementById("hwOutput");

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

    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
        log(`Created Person: ${this.name}, Age: ${this.age}`);
      }
      greet() {
        log(`Hello! My name is ${this.name}.`);
      }
    }

    class Book {
      constructor(title, author, pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
        this.pagesRead = 0;
        log(`Created Book: "${this.title}" by ${this.author}, ${this.pages} pages`);
      }
      read(pages) {
        this.pagesRead += pages;
        log(`Read ${pages} pages of "${this.title}". Total read: ${this.pagesRead}`);
      }
      isLongBook() {
        return this.pages > 300;
      }
    }

    class Car {
      constructor(make, model, fuel) {
        this.make = make;
        this.model = model;
        this.fuel = fuel;
        log(`Created Car: ${this.make} ${this.model}, Fuel: ${this.fuel}`);
      }
      drive(distance) {
        this.fuel = Math.max(0, this.fuel - distance/10);
        log(`${this.make} ${this.model} drove ${distance} km. Fuel left: ${this.fuel.toFixed(2)}`);
      }
      refuel(amount) {
        this.fuel += amount;
        log(`${this.make} ${this.model} refueled ${amount}. Fuel now: ${this.fuel.toFixed(2)}`);
      }
      static info() {
        log("Cars are vehicles.");
      }
    }

    class ElectricCar extends Car {
      constructor(make, model, fuel, battery) {
        super(make, model, fuel);
        this.battery = battery;
        log(`ElectricCar Battery: ${this.battery}`);
      }
      charge(amount) {
        this.battery += amount;
        log(`${this.make} ${this.model} charged by ${amount}. Battery now: ${this.battery}`);
      }
    }

    const person1 = new Person("Pranay", 14);
    const book1 = new Book("JavaScript Mastery", "Pranay", 350);
    const car1 = new Car("Toyota", "Corolla", 50);
    const eCar1 = new ElectricCar("Tesla", "Model X", 10, 70);

    person1.greet();
    book1.read(50);
    log(`Is "${book1.title}" a long book? ${book1.isLongBook()}`);
    car1.drive(100);
    car1.refuel(20);
    ElectricCar.info();
    eCar1.drive(50);
    eCar1.charge(30);

  })();
  </script>
</body>
</html>

Homework - Classes & Methods