HQ is a special building that can produce other buildings. It keeps track of all the buildings it had built up until now. The same type of building can be built more than once:
class HQ {
val buildings = mutableListOf<Building<*, Unit>>()
fun buildBarracks(): Barracks {
val b = Barracks()
buildings.add(b)
return b
}
fun buildVehicleFactory(): VehicleFactory {
val vf = VehicleFactory()
buildings.add(vf)
return vf
}
}
All other buildings produce units. Units can be either infantry or armored vehicle:
interface Unit
interface Vehicle : Unit
interface Infantry : Unit
Infantry can be either riflemen or rocket soldier:
class Rifleman : Infantry
class RocketSoldier : Infantry
enum class InfantryUnits {
RIFLEMEN,
ROCKET_SOLDIER
}
Here we see the enum keyword for the first time. Vehicles are either tanks or armored personnel carriers (APCs):
class APC : Vehicle
class Tank : Vehicle
enum class VehicleUnits {
APC,
TANK
}
A barracks is a building that produces infantry:
class Barracks : Building<InfantryUnits, Infantry> {
override fun build(type: InfantryUnits): Infantry {
return when (type) {
RIFLEMEN -> Rifleman()
ROCKET_SOLDIER -> RocketSoldier()
}
}
}
A vehicle factory is a building that produces different types of armored vehicles:
class VehicleFactory : Building<VehicleUnits, Vehicle> {
override fun build(type: VehicleUnits) = when (type) {
APC -> APC()
TANK -> Tank()
}
}
We can make sure that we can build different units now:
val hq = HQ()
val barracks1 = hq.buildBarracks()
val barracks2 = hq.buildBarracks()
val vehicleFactory1 = hq.buildVehicleFactory()
And now on to producing units:
val units = listOf(
barracks1.build(InfantryUnits.RIFLEMEN),
barracks2.build(InfantryUnits.ROCKET_SOLDIER),
barracks2.build(InfantryUnits.ROCKET_SOLDIER),
vehicleFactory1.build(VehicleUnits.TANK),
vehicleFactory1.build(VehicleUnits.APC),
vehicleFactory1.build(VehicleUnits.APC)
)
We've already seen the listOf() function from the standard library. It will create a read-only list of different units that our buildings produce. You can iterate over this list and make sure that those are indeed the units we require.