The Shield Generator
Stardate 55143.0 ยท UES Magnanimous
Briefing
Commander Raghunathan is back, with a copy of the other ship's computer, and the first thing she wants is our own shields to work properly before anyone reads it. The shield routine has no memory: every hit is treated as the first, so the display reads "98%" after ninety hits.
Chief T'Kala wants a shield generator that knows its charge. It takes hits, which reduce it but never below zero. It recharges, but never past capacity. It reports a whole-number percentage, rounded down, and it can say plainly whether it is down. Four small behaviours, one object, and a memory.
Mission objectives
ARCHIE checks all five every time you run diagnostics.
- โขA new generator starts at full charge, 100%
- โขA hit reduces the charge; two hits reduce it twice
- โขCharge never drops below zero, and is_down reports it
- โขRecharging never exceeds capacity
- โขPercent is a whole number, rounded down
Objective
Write a class Shields:
Shields(capacity)starts fully charged..hit(damage)reduces the charge, never below 0..recharge(amount)increases it, never above capacity..percent()returns the charge as a whole-number percentage of capacity, rounded down..is_down()returnsTruewhen the charge is 0.
Press Run Diagnostics and I will tell you which objectives you actually met.
Objective
Write a struct Shields with:
Shields::new(capacity: u32) -> Shields, fully charged.fn hit(&mut self, damage: u32): reduce the charge, never below 0.fn recharge(&mut self, amount: u32): increase it, never above capacity.fn percent(&self) -> u32: charge as a whole-number percentage, rounded down.fn is_down(&self) -> bool: true when the charge is 0.
Press Run Diagnostics and I will tell you which objectives you actually met.
Ask Commander Raghunathan for a hint
Store the capacity and the current charge as attributes. hit subtracts and clamps at 0; recharge adds and clamps at capacity; percent is charge times 100, integer-divided by capacity.
Debrief
The shields remember. After ninety hits they read 10%, which is honest, and after a recharge they read 100% and not 140%, which is progress. Commander Raghunathan has put the other computer's core on the science bench and has not yet turned it on.