Facebook Pixel

Exercise: Factory

This exercise puts the Factory pattern into code.

Scenario

You are building a small game engine. The game spawns enemies of three types — goblin, orc, and dragon — each with different hit points and a gold reward paid out when the enemy is defeated. An EnemyFactory is responsible for constructing the right enemy object given a type name; the rest of the game asks the factory for an enemy and then works with the returned object. A Game class tracks all living and defeated enemies by name, accumulates gold as enemies fall, and answers queries about current state.

Commands

The program reads a list of commands, one per line, and prints one line of output per command.

CommandOutput
["spawn", type, name]"Spawned <name> the <type> (<hp> HP)" — or "Unknown enemy: <type>" if the type is not recognized
["hit", name, dmg]"<name> not found" if the name is unknown; "<name> is already defeated" if already at zero HP; "<name> defeated (+<reward> gold)" if the hit reduces HP to zero; "<name>: <hp> HP" otherwise
["status", name]"<name> not found" if unknown; "<name>: defeated" if defeated; "<name>: <hp> HP" if alive
["gold"]"Gold: <total>" — the sum of rewards for all defeated enemies so far

Enemy stats: goblin = 30 HP / 10 gold, orc = 60 HP / 25 gold, dragon = 200 HP / 100 gold.

Example
Input
6
spawn goblin Grub
spawn dragon Ryxis
hit Grub 10
hit Grub 25
status Ryxis
gold
Output
Spawned Grub the goblin (30 HP)
Spawned Ryxis the dragon (200 HP)
Grub: 20 HP
Grub defeated (+10 gold)
Ryxis: 200 HP
Gold: 10
Explanation
The factory builds a goblin with 30 HP and a dragon with 200 HP. The first hit takes Grub to 20 HP. The second hit of 25 would drop Grub below zero, so its HP floors at 0 and Grub is defeated, paying out its 10 gold. Ryxis has not been touched, so its status is still 200 HP, and `gold` reports the running total of 10.

Your task

Implement the skeleton in the editor below so the commands produce the output described above.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro