Challenge

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Inventory Class

Model the player's bag as a class that manages its own items and enforces a capacity.

Step 1: `Bag` takes a `capacity`. Its constructor sets `items` to an empty array. Step 2: `add(item)` pushes the item and prints `"Added item"` if there is room, otherwise prints `"Bag full, dropped item"`. It returns the instance either way. Step 3: `count()` returns the number of items, and `has(item)` returns whether the item is inside. Step 4: create a bag of capacity 2, then in one chained line add Potion, Map and Rope. Print `"Items: N"` and `"Has Rope: X"`.

Expected output:

Added Potion Added Map Bag full, dropped Rope Items: 2 Has Rope: false
Starter code
// Write your class here // Use it here

Exercise 2 — Codémon Arena

Run a small arena where a normal Codémon and a legendary one fight, using inheritance so the shared code is written once.

Step 1: `Codemon` takes a name and hp. `takeDamage(amount)` lowers hp, never below 0. `isAlive()` returns whether hp is above 0. `power()` returns 10. Step 2: `Legendary extends Codemon`. Its `power()` returns the parent's power times 3. Step 3: `fight(a, b)` makes them hit each other in turns, `a` first, each hit dealing the attacker's power, until one is no longer alive. Each hit prints `"attacker hits defender, defender at X"`. Step 4: fight Zap (30 HP) against a legendary Titanchu (50 HP), then print `"Winner: name"`.

Expected output:

Zap hits Titanchu, Titanchu at 40 Titanchu hits Zap, Zap at 0 Winner: Titanchu
Starter code
// Write your classes and the fight function here // Run the fight here

Exercise 3 — Shop Item Hierarchy

Model shop items as a class family, load them from raw data, and total a cart where some items are on sale.

Step 1: `Item` takes a name and a price. `cost()` returns the price. `label()` returns `"name: X gold"` using `cost()`. Step 2: `SaleItem extends Item`. Its `cost()` returns half the parent's cost. Its `label()` reuses the parent's label and adds `" (sale)"`. Step 3: build `cart` from `raw`: entries with `sale` set to `true` become `SaleItem`, the others `Item`. Step 4: print each label, then `"Total: X gold"` with the sum of the costs, then `"On sale: N"` using `instanceof`.

Expected output:

Potion: 30 gold Elixir: 60 gold (sale) Map: 40 gold Total: 130 gold On sale: 1
Starter code
const raw = [ { name: "Potion", price: 30, sale: false }, { name: "Elixir", price: 120, sale: true }, { name: "Map", price: 40, sale: false } ]; // Write your classes here // Build the cart and report here
Back to the course