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

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
let anishTheDice = new Dice(6);  // Yes I'm using Anish for my dice

// CALL THE ROLL METHOD A FEW TIMES AND PRINT THE RESULTS
console.log(anishTheDice.roll());
console.log(anishTheDice.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!

%%html

<p id="output"></p>
<button onclick="window.myPet.arya()">ARYA (Don't do this)</button>
<button onclick="window.myPet.jump()">JUMP</button>
<button onclick="window.myPet.wait()">WAIT</button>

<script>
  window.output = document.querySelector("#output");

  // Define our Pet class :) <-- At least it isn't Anish this time
  window.Pet = class {
    constructor(name) {
      this.name = name;
      this.sanity = 5;
      this.patience = 5;
      this.tiredLevel = 5;
    }

    jump() {
      this.sanity++;
      this.tiredLevel++;
      console.log(`Sanity: ${this.sanity}; Patience: ${this.patience}; Tired Level: ${this.tiredLevel}`);
    }

    wait() {
      this.sanity--;
      this.patience--;
      console.log(`Sanity: ${this.sanity}; Patience: ${this.patience}; Tired Level: ${this.tiredLevel}`);
    }

    arya() {
      this.name = "Arya";
      this.sanity = -100;
      this.patience = 100;
      this.tiredLevel = -10000;
      console.log(`Sanity: ${this.sanity}; Patience: ${this.patience}; Tired Level: ${this.tiredLevel}`);
    }
  }

  window.myPet = new window.Pet("Anish");  // <-- (jk it was Anish)
</script>

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

// 1
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  // 2
  greet() {
    console.log(`Hello, ${this.name}!`);
  }
}
let anish = new Person("Anish", 5);  // ANISH IS BACK!
console.log(`${anish.name} is ${anish.age} years old!`);

// 3
class Book {
  constructor(title, author, pages) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.pagesRead = 0;
  }
  // 4
  read(pages) {
    this.pagesRead += pages;
    if (this.pagesRead >= this.pages) {
      console.log("You finished reading the book!");
      this.pagesRead = this.pages;
    } else {
      console.log(`You've just read ${pages} pages, bringing you to a grand total of ${this.pagesRead}!`);
    }
  }
  // 5
  isLongBook() {
    return this.pages > 300;
  }
}
let anishsBook = new Book("How Anish Formed Anishiapolis", "Anish Gupta", 301);
console.log(`(True/False) Anish's book is long: ${anishsBook.isLongBook()}`);

// 6
class Car {
  constructor(make, model, fuel) {
    this.make = make;
    this.model = model;
    this.fuel = fuel;
  }
  drive(distance) {
    this.fuel -= distance;
    if (this.fuel < 0) {
      console.log(`You couldn't drive the full distance since you ran out of fuel :(`);
      this.fuel = 0;
    } else {
      console.log(`You drove ${distance} units! You now have ${this.fuel} of fuel units left :)`);
    }
  }
  refuel(fuel) {
    this.fuel += fuel;
    console.log(`You gained ${fuel} fuel units, and now have a total of ${this.fuel}!`);
  }
  // 7
  info() {
    console.log("INFO> Just in case you didn't know, cars are vehicles!");
    console.log(`INFO> This car is: ${this.make} ${this.model}`);
  }
}

let anishsCar = new Car("AnishCar", "All-Anish-V", 30);
anishsCar.info();
console.log(`Fuel: ${anishsCar.fuel}`);

// 8
class ElectricCar extends Car {
  constructor(make, model, battery) {
    super(make, model);
    this.battery = battery;
  }
  charge(ammount) {
    this.battery += ammount;
    console.log(`The battery has been charged by ${ammount} and is now at ${this.battery}!`);
  }
}
let anishsECar = new ElectricCar("AnishCar", "All-Anish-E", 30);

// 9
anish.greet();
anishsBook.read(200);
anishsCar.drive(28)
anishsECar.charge(3);

// 10


<IPython.core.display.Javascript object>