I wanted to design a system for creating different types of Plants (inspired by plants vs zombies) in an organized way. To simplify the addition of new plant Types, I aimed to make the cost and damage of each plant static so it could be set once for all Plants of that type.
At the moment, I only have one Plant called Sunflower, and now I want to instantiate the Sunflowerplant in the build method within the Cell class.
However, when attempting this approach, I encountered the error:
Cannot create an instance of an abstract class.
This issue makes sense to me. Is there a way to ensure that only non-abstract classes which extend from Plant can be passed as a Parameter for the build()
method, or do I need to implement some kind of if (!c isAbstract)
check?
abstract class Plant {
public static dmg: number;
public static cost: number;
constructor(cell: Cell) {
this.cell = cell;
}
cell: Cell;
}
// More Plant types could be created like this
class Sunflower extends Plant {
public static dmg = 0;
public static cost = 50;
cell: Cell;
constructor(cell: Cell) {
super(cell);
}
}
class Cell {
build(c: typeof Plant) {
if (c.cost <= game.money) {
this.plant = new c(this); //Cannot create an instance of an abstract class.
game.money -= c.cost;
}
}
}
// Example of building plants
let c = new Cell();
c.build(Sunflower);