C # subclass best practices

I'm currently working on a game in XNA, and I'm not sure how I should do the following ...

I have a base class of buildings as such

public class BuildingsBase { private int _hp; public int hp { get { return _hp; } set { _hp= value; } } private int _woodRequired; public int woodRequired { get { return _woodRequired; } set { _woodRequired = value; } } } 

Then I have several subclasses for building types, for example.

 public class TownHall:BuildingsBase { public int foodHeld; public TownHall() { foodHeld = 100; woodRequired = 500; } } 

My question is what is the best way to set default values ​​for subclassing.

For example, woodRequired for townhall is set to 500, but in different places in the code I need to access this value before I get an instance of townhall (when checking if there is a tree for the assembly).

I currently have a global array of default variables for each type of building, but they are wondering if there is a better way to do this.

 if (Globals.buildingDefaults[BuildingType.Townhall].woodRequired < Globals.currentWood) { Townhall newTH = new Townhall(); } 
+5
source share
1 answer

What usually happens is that they create flies ( see figure ). This object contains properties that are in any case the same for each instance. There is no need to change (or actually store) the required amount of wood for each instance separately.

In a very basic design, it will look like this:

 class BuildingTemplate { public int WoodRequired { get; set; } } class Templates { public static BuildingTemplate TownHall { get; set; } } 

In the end, you should call a method like:

 public bool CanBuildTownHall(Player player) { return player.HasEnoughResources(Templates.TownHall); } 

Of course, you can use the dictionary to extract the template, and players should not be aware of the building requirements. I just illustrate the template here.

If the player has enough resources, you can use the template to subtract the amount and create the actual TownHall instance. It is nice to have a link to the actual template, because you are likely to access other global properties that are also valid for all TownHall (for example, audio / visual //.).//

 class TownHall { public TownHall(BuildingTemplate template) { _template = template; } } 
+4
source

Source: https://habr.com/ru/post/1245308/


All Articles