Exercise: Space Fleet
Finish the classes behind a space shooter's fleet, a Ship with private shields, a Fighter that extends it and a Fleet that reports who can fly, and let the tests check each one.
Journeyman · JavaScript · OOP · Updated
Red Squadron is the player's fleet in a space shooter game, and its code isn't finished. The ships' shields can be changed by anyone, a tank can be "refueled" with negative fuel, the fighters can't fire, and the fleet's roll call crashes. You'll finish three classes, Ship, Fighter and Fleet, using everything in this chapter: methods and this, a class with a private field and a getter, a child class that extends its parent, and an arrow function that keeps this. Tests check every piece as you go.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-javascript-space-fleet, also linked from the Exercise box beside the lesson. Clone it into a folder for this course. In a terminal, in that folder:
git clone https://github.com/ask-codey/exercise-javascript-space-fleet.git
Git makes a folder, exercise-javascript-space-fleet, with the exercise code inside.
The folder holds:
ship.js: theShipclass (problems 1 to 4), a finishedFreighterclass to learn from, and the start ofFighter(problem 5).fleet.js: theFleetclass (problems 6 and 7).mission.js: Red Squadron's mission log. It builds a fleet from your classes and prints what happens. Ready to use.ship.test.jsandfleet.test.js: the tests. You don't need to change these.
Open the folder in VS Code. All you need is Node.js; there's nothing to install.
What to do
Every problem sits in a comment, with what the code should do and examples. Some methods are already written and return a placeholder for now, such as takeHit:
/*
* 3. Take a hit: lower the shields by the damage, but never below 0.
* Return the shields that are left.
*
* A ship with 100 shields: takeHit(30) -> 70, then takeHit(50) -> 20, then takeHit(50) -> 0
*/
takeHit(damage) {
return 0;
}
- Make the shields private (problem 1). Declare
#shieldsat the top ofShipand store the shields in it. - Give the shields a getter (problem 2), so other code can read
ship.shieldsbut not change it. - Finish
takeHitandrefuel(problems 3 and 4).refuelrefuses an amount less than 0, and never fills pastShip.MAX_FUEL. - Finish
Fighter(problem 5): a constructor that passes the ship's details toShip, afire()method, and adescribe()that adds the missiles toShip's line. - Finish
readyToFly(problem 6): the names of the ships that can still fly. - Fix
rollCall(problem 7). Runnode mission.jsfirst and read the error it gives.
Check your work
Open VS Code's terminal with Terminal > New Terminal, and run the tests:
node --test
At first every test fails. That's expected: each problem you solve turns its tests green. When a test fails, its message says which problem it is and what it expected, for example Problem 4: refuel(-10) should return false.
To watch your classes at work, run the mission log:
node mission.js
At first it stops at the roll call with a TypeError. That's the bug in problem 7, and once problems 5 and 7 are done, the whole log prints.
Hints
- Read
Freighterbefore you writeFighter. It's a finished class that extendsShip, andFighterfollows the same pattern:super(...)first, then its own property, then an override ofdescribethat starts fromsuper.describe(). Inheritance with extends and super walks through it. - Two methods already read
this.shields. After problem 1,canFlyanddescribewould break, until the getter from problem 2 givesshieldsback to them. Private Fields, Getters and Setters shows a getter beside a private field. - A limit is a job for
Math.maxorMath.min.Math.max(0, number)never goes below 0, andMath.min(Ship.MAX_FUEL, number)never goes above the top. - Can it fire? A fighter fires only when it can fly and has a missile. Every ship already has a
canFlygetter you can ask, throughthis. - Who's before the dot? In
rollCall,mapcalls the inner function with no object before the dot. Losing this, and How Arrow Functions Help shows the kind of function that takesthisfrom the code around it, wherethisis the fleet.
When you're done
Every test is green, and node mission.js prints:
Ships in the fleet: 3
--- Roll call ---
Red Squadron: Comet
Red Squadron: Vega
Red Squadron: Mule One
--- Battle ---
Comet fires! Missiles left: 2
Vega fires! Missiles left: 0
Vega can't fire
Vega takes a hit. Shields left: 0
Comet takes a hit. Shields left: 70
--- Supply run ---
Mule One unloads 15 crates
Mule One refuels -10: refused
Mule One refuels 90: done
--- Status ---
Comet: shields 70, fuel 40, missiles 2
Vega: shields 0, fuel 10, missiles 0
Mule One: shields 150, fuel 100, cargo 25 crates
Ready to fly: Comet, Mule One
Now look back at your Fighter. If Ship's describe added the ship's speed tomorrow, would your fighter's line pick it up without a change? If it would, you reused the parent's work the way inheritance intends.
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. You don't need Git for this: you upload your files in the browser, as the lesson Put Your Code on GitHub (Module 1) shows screen by screen.
- On GitHub, click +, then New repository. (No account yet? Sign up at github.com: it's free.) Name it (for example
exercise-javascript-space-fleet), choose Public, turn Add README on so the upload button appears, and click Create repository. Your folder's own README replaces GitHub's when you upload it. - Choose Add file, then Upload files. In your exercise folder, select everything (Ctrl+A, or Cmd+A on a Mac) and drag it onto the upload area. Drag what's inside the folder, not the folder itself, so
package.jsonlands at the top of your repo. - Under Commit changes, type a short note, such as My solution, and choose Commit changes.
- Paste your repo's address, such as
https://github.com/your-name/exercise-javascript-space-fleet, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Upload the changed files again (each one replaces the file with the same name), commit, and submit again: your latest submission is the one that counts.
So what
A class that guards its own data, a child class that adds only what's new, and a group object that asks each member a question: that's the shape of most game code, and of shopping carts, playlists and dashboards too. The Virtual Pet project at the end of this module is built the same way.