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

<div id="ph1output"></div>

<script>
(() => {

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

    class TennisPlayer { 
        // I was going to do tournamentsPlayed but I couldn't find an exact value for Djokovic
        constructor(name, rank, rankPoints, age, titlesWon, winRate) {
            this.name = name;
            this.rank = rank;
            this.rankPoints = rankPoints;
            this.age = age;
            this.titlesWon = titlesWon;
            this.winRate = winRate;
        };
        profile() {
            // basically made the profile look better, also it returns to be more flexible with the program
            return `--- ${this.name.toUpperCase()} ---
> Age: ${this.age} years
> Rank: #${this.rank}
> Rank points: ${this.rankPoints} points
> Titles Won: ${this.titlesWon}
> Win Rate: ~${Math.round(this.winRate*100)}%`;
            
            // "Hi my name is " + this.name + ", my rank is " + this.rank + " and I have " + this.rankPoints + " ranking points.";
        }

        showProfile() {
            let profileData = this.profile();
            output.innerText += "\n" + profileData;
            console.log(profileData);
        }

    };
    //Call the class here

    // create an instance of the class
    novak = new TennisPlayer("Novak Djokovic", 1, 16000, 38, 100, 1159/(1159+233));
    novak.showProfile()

})();

</script>

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

<h3>DNHS Library</h3>
<div id="ph2output_demo"></div>

<br>
<h4>Interactive  Buttons</h4>

<button id="showCatalogButton">Show catalog</button>
<br>
<input type="text" id="addBookTitle" placeholder="Enter the book title to add">
<button id="addBookButton">Add book</button>
<br>
<input type="text" id="removeBookTitle" placeholder="Enter the book title to remove">
<button id="removeBookButton">Remove book</button>

<hr>

<button id="showComputersButton">Show all computers</button>
<br>
<button id="getPoweredCompsButton">Get # of powered on computers</button>
<br>

<input type="number" id="togglePowerID" placeholder="ID of computer to turn on/off">
<button id="togglePowerButton">Toggle power</button>
<br>


<div id="ph2output_interactive"></div>


<script>
(() => {

    let output = document.getElementById("ph2output_demo");

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

    // Step 1: Create the main class called Library
    class Library {
        constructor(name) {
            this.name = name;
            writeOutput(`Welcome to the ${this.name} library!`)
        }

        // Step 2: Create an inner class called Book
        static BookCatalog = class {
            //create a constructor with that takes the this.books argument.
            constructor(books){
                this.books = books;
            }

            addBook(title) {
                this.books.push(title);
                writeOutput(`Added "${title}" to the library.`);
            }

            removeBook(title) { 
                const index = this.books.indexOf(title);
                if (index > -1) {
                    this.books.splice(index, 1);
                    writeOutput(`Removed "${title}" from the library.`);
                } else {
                    writeOutput(`"${title}" not found in the library.`);
                }
            }

            showCatalog(){
                writeOutput(`Book catalog: ${this.books}`);
            }
        }

        // Step 3: Create another inner class called Computers
        static Computers = class {

            // basically I added a feature where u can track an entire database of computers and their information

            // TODO: Create a constructor that takes computersOn as an argument
            // i kinda reworked this to be more vertasile so it tracks
            // all the computers information

            constructor(allComputers){
                this.allComputers = allComputers; // basically just keep track of every computer in the library
                this.computersOn = 0;
                this.allComputers.forEach(element => {
                    if (element[2]){
                        this.computersOn ++;
                    }
                });
            }

            // TODO: Create a method that outputs the number of computers on
            showComputersOn(){
                writeOutput(`There ${this.computersOn==1 ? "is":"are"} ${this.computersOn} computer(s) on`);
            }

            // added this method that turns computers on and off
            toggleComputerPower(computerid){
                this.allComputers.forEach(element => {
                    if (element[0] == computerid){
                        let currentPower = element[2];
                        if (currentPower){
                            this.computersOn -= 1;
                        } else {
                            this.computersOn += 1;
                        }

                        element[2] = !element[2];

                        writeOutput(`Turned on ${element[1]} (ID: ${element[0]})`);
                        
                    }
                });


            }

            showAllComputers(){
                let currentmsg = "";
                this.allComputers.forEach(element => {
                    currentmsg += `ID ${element[0]} - ${element[1]} - ${element[2] ? "ON":"OFF"}\n`;
                });
                writeOutput(currentmsg);
            }

        }

    }


    const myLibrary = new Library("downtown");
    const bookManager = new Library.BookCatalog(["Harry Potter", "Dune"]);
    const techRoom = new Library.Computers([
        // [id,type of computer, is powered on]
        [1, "Dell OptiPlex", false],
        [2, "Dell OptiPlex", false],
        [3, "HP All-in-One", false],
        [4, "HP Slimline", true],
        [5, "HP Slimline", true]
    ]);

    bookManager.addBook("The Hobbit");
    bookManager.addBook("1984");
    bookManager.removeBook("The Hobbit");
    bookManager.showCatalog();

    writeOutput(""); // blank line

    techRoom.showAllComputers();
    techRoom.toggleComputerPower(1);

    techRoom.toggleComputerPower(1);
    techRoom.showAllComputers();
    techRoom.showComputersOn();
    
    // switch to interactive (there are two divs for demo and interactive because I wanted the demo
    // followed by buttons, followed by text specifically from the interacive buttons

    output = document.getElementById("ph2output_interactive") // now, since everything uses output, it will appear below the buttons

    // button handling... i forgot why i decided to do this but its too late to back out now o7

    document.getElementById("showCatalogButton").addEventListener("click", () => {
        bookManager.showCatalog();
    });

    document.getElementById("addBookButton").addEventListener("click", () => {
        let titleToAdd = document.getElementById("addBookTitle").value;
        // if its empty or only spaces
        if (titleToAdd.trim().length > 0){
            bookManager.addBook(titleToAdd);
        } else {
            alert("Please enter a book title!");
        }
    });

    document.getElementById("removeBookButton").addEventListener("click", () => {
        let titleToRemove = document.getElementById("removeBookTitle").value;
        // if its empty or only spaces
        if (titleToRemove.trim().length > 0){
            bookManager.removeBook(titleToRemove);
        } else {
            alert("Please enter a book title!");
        }
    });

    // tech room buttons
    document.getElementById("showComputersButton").addEventListener("click", () => {
        techRoom.showAllComputers();
    });

    document.getElementById("getPoweredCompsButton").addEventListener("click", () => {
        techRoom.showComputersOn();
    });

    document.getElementById("togglePowerButton").addEventListener("click", () => {
        let idNum = document.getElementById("togglePowerID").value;
        if (!isNaN(idNum)) {
            idNum = Number(idNum);
            let allIds = techRoom.allComputers.map(compinfo => compinfo[0]);
            if (idNum in allIds){
                techRoom.toggleComputerPower(idNum);
            } else {
                alert("Enter a VALID computer ID")
            }
        } else {
            alert("Please  enter the ID of the computer to power on/off")
        }
    });

    


    




})();

</script>

DNHS Library


Interactive Buttons







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

<div id="hwoutput"></div>

<script>
(() => {

	function writeOutput(msg){
		document.getElementById("hwoutput").innerText += "\n" + msg;
	}
	
	class Upgrade {
		constructor(name, multiplier) {
			this.name = name;
			this.multiplier = multiplier;
		}

		applyUpgrade(game) {
			const original = game.cookiesPerClick;
			game.cookiesPerClick *= this.multiplier;
			writeOutput(`${this.name} applied. Cookies per click increased from ${original} to ${game.cookiesPerClick}.`);
		}
	}

	class CookieClicker {
		constructor(cookieType = "Chocolate Chip") {
			this.cookies = 0;
			this.cookiesPerClick = 1;
			this.cookieType = cookieType;
		}

		click() {
			this.cookies += this.cookiesPerClick;
			writeOutput(`You clicked a ${this.cookieType} cookie, total cookies: ${this.cookies}`);
		}

		addUpgrade(upgrade) {
			upgrade.applyUpgrade(this);
		}
	}

	const game = new CookieClicker("Oatmeal Raisin");
	game.click();
	game.click();

	const doubleClick = new Upgrade("Double Click", 2);
	game.addUpgrade(doubleClick);

	game.click();

	const tripleClick = new Upgrade("Triple Click", 3);
	game.addUpgrade(tripleClick);

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

})();
</script>

This is where you will find homework: Github Homework Link