JavaScript Classes and Constructors Homework

By now you should have a decent grasp of classes and constructors, and how to make and build one. The following exercises should help you solidify your understanding of classes and constructors in JavaScript.

Popcorn Hack 1

  1. The class TennisPlayer has been defined for you. Create a constructor with the arguements name, rank, and rankPoints.
  2. Call the class with the arguments Novak Djokovic, 1, 16000.
  3. Add one or more of the following arguments to the initial constructor: age, tournamentsPlayed, titlesWon. Add this as part of the profile output.
%%html

<p>Tennis Player Profiles</p>

<div id="outputPH1">Results will appear here:<br></div>

<script>

(() => {

const output = document.getElementById("outputPH1");
 
class TennisPlayer {
    constructor(name, rank, rankPoints, age, titlesWon) {
        this.name = name;
        this.rank = rank;
        this.rankPoints = rankPoints;
        this.age = age;
        this.titlesWon = titlesWon;
    };
    profile () {
        console.log("Hi, my name is " + this.name + ", my rank is " + this.rank + ". I have " + this.rankPoints + " ranking points and I am " + this.age + " years old. I have won " + this.titlesWon + " titles so far.");
        output.innerText += "\nHi, my name is " + this.name + ", my rank is " + this.rank + ". I have " + this.rankPoints + " ranking points and I am " + this.age + " years old. I have won " + this.titlesWon + " titles so far.";
    }

};

const player1 = new TennisPlayer("Novak Djokovic", 1, 12000, 38, 100);
const player2 = new TennisPlayer("Aryna Sabalenka", 2, 10400, 27, 21);
const player3 = new TennisPlayer("Carlos Alcaraz", 3, 11540, 22, 24);
const player4 = new TennisPlayer("Rafael Nadal", 4, 9850, 39, 92);

player1.profile();
player2.profile();
player3.profile();
player4.profile();

})();

</script>

Tennis Player Profiles

Results will appear here:

Popcorn Hack 2

  1. Create a class called library
  2. Within library create a class called book with a constructors that allows the two methods - add book and remove book
  3. Add another inner class called computers - and have it output the number of computers on

Below is the starter code to get you started

%%html

<p>Library System</p>

<div id="outputPH2">Results will appear here:<br></div>

<script>
(() => {

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

// Step 1: Create the main class called Library
class Library {
    constructor(name) {
        this.name = name;
        console.log(`Welcome to the ${this.name} Library!`);
        output.innerText += `\nWelcome to the ${this.name} Library!`;
    }

    // Step 2: Create an inner class called Book
    static Book = class {
        constructor() {
            this.books = [];
        }

        addBook(title) {
            this.books.push(title);
            console.log(`Added "${title}" to the library.`);
            output.innerText += `\nAdded "${title}" to the library.`;
        }

        removeBook(title) { 
            const index = this.books.indexOf(title);
            if (index > -1) {
                this.books.splice(index, 1);
                console.log(`Removed "${title}" from the library.`);
                output.innerText += `\nRemoved "${title}" from the library.`;
            } else {
                console.log(`"${title}" not found in the library.`);
                output.innerText += `\n"${title}" not found in the library.`;
            }
        }
    }

    // Step 3: Create another inner class called Computers
    static Computers = class {
        constructor(computersOn) {
            this.computersOn = computersOn;
        }

        showComputersOn() {
            console.log(`There are ${this.computersOn} computers currently on.`);
            output.innerText += `\nThere are ${this.computersOn} computers currently on.`;
        }
    }
}

// --- Example Usage ---
const myLibrary = new Library("Downtown");
const bookManager = new Library.Book();
const techRoom = new Library.Computers(8);

bookManager.addBook("The Hobbit");
bookManager.addBook("1984");
bookManager.removeBook("The Hobbit");
techRoom.showComputersOn();

})();
</script>

Library System

Results will appear here:

Homework

Create and expand the Cookie Clicker project:

  1. Fill out the cookies and cookiesPerClick variables.
  2. Define what should happen upon clicking the cookie.
  3. Create an Upgrade class that multiplies cookies per click, and expand the original cookieclicker class to integrate upgardes.
  4. Print how each upgrade changes the total cookie output.
  5. Add a cookie type variable which sets the specific type of cookie (ex: Chocolate chip, Oatmeal, etc.) The following code is to help you get started.

Extra credit: Up to 0.03 points

  • Create a new cell, apply the ALL of the above changes to a blank cookie clicker project, and submit that code for the cookie clicker project.
%%html

<p>Cookie Clicker Game</p>

<div id="outputHW">Results will appear here:<br></div>

<script>

(() => {

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

// Create cookie clicker class
class CookieClicker {
  constructor(cookies = 0, cookiesPerClick = 1, cookieType = "Chocolate Chip") {
    this.cookies = cookies;
    this.cookiesPerClick = cookiesPerClick;
    this.cookieType = cookieType;
    output.innerText += `\nStarting a new game with ${this.cookieType} cookies!`;
  }

  // Define what happens upon clicking the cookie
  click() {
    this.cookies += this.cookiesPerClick;
    console.log(`You have ${this.cookies} ${this.cookieType} cookies.`);
    output.innerText += `\nYou have ${this.cookies} ${this.cookieType} cookies.`;
  }

  // Apply any upgrades to the cookies per click
  applyUpgrade(upgrade) {
    this.cookiesPerClick *= upgrade.multiplier;
    console.log(`Upgrade applied: ${upgrade.name} (x${upgrade.multiplier} per click)`);
    output.innerText += `\nUpgrade applied: ${upgrade.name} (x${upgrade.multiplier} per click)`;
  }
}

// Update class
class Upgrade {
  constructor(name, multiplier) {
    this.name = name;
    this.multiplier = multiplier;
  }

  // The updates show effects of upgrades
  showEffect(basePerClick) {
    const newRate = basePerClick * this.multiplier;
    console.log(`${this.name} changes cookies per click from ${basePerClick} to ${newRate}`);
    output.innerText += `\n${this.name} changes cookies per click from ${basePerClick} to ${newRate}`;
  }
}

// --- Example Usage ---

const game = new CookieClicker(0, 1, "Chocolate Chip");

game.click();
game.click();

// Create upgrades
const doubleClick = new Upgrade("niha the cookie muncher", 2);
const megaOven = new Upgrade("hota the cookie monster", 3);
const cookieFactory = new Upgrade("jha the cookie factory", 5);

// Show and apply upgrades
doubleClick.showEffect(game.cookiesPerClick);
game.applyUpgrade(doubleClick);
game.click();

megaOven.showEffect(game.cookiesPerClick);
game.applyUpgrade(megaOven);
game.click();

cookieFactory.showEffect(game.cookiesPerClick);
game.applyUpgrade(cookieFactory);
game.click();

})();
</script>

Cookie Clicker Game

Results will appear here:

This is where you will find homework: Github Homework Link