On Sunday, 20 March 2022 at 05:44:44 UTC, Salih Dincer wrote:
> On Sunday, 20 March 2022 at 01:28:44 UTC, Era Scarecrow wrote:
> Inheritance and Polymorphism is one of the hardest things to grasp mostly because examples they give in other books of 'objects' is so far unrelated to software that it doesn't really compare.
You are right, difficult model yet so abeyant. Moreover, there is a lot of freedom given in D. I think OOP alone is not worth 5 cents without design patterns.
OOP can be aggressive like a dog. I think D should be a little more rigid on OOP.
Actually one good example for Objects is a game, specifically Magic The Gathering.
MTG is a card game, of that everyone knows. But there's so many effects. When it comes into play, when it goes to the graveyard, if it gets exiled, cost to cast it from the gaveyard/exile, tapping, untapping, paying and tapping to do an ability, milling cards, drawing cards, scrying cards, attacking without untapping, deathtouch, islandwalk. Then there's enchantments, equipment, passive always active abilities (all your creatures get +0/+1) and a myriad of other things.
Now with that out of the way making a base 'card' with all it's actions as a mere interface and then making each card individually OR inheriting from a base card using polymorphism would be a great way to do things.
Going the one route
abstract class Card {
string name, description, picture, quote;
string types; //Green Insect Token, Indestructable, etc
int basePower, baseToughness;
Card[] enchantments; //affecting this card specifically
static Card[] globalEnchantments, //affecting all cards
playerEnchantments; //affecting only my own cards
//When a card leaves play remove from enchantments list.
//globals will just remove from the static list
void purgeCard(Card target);
//calculate power
int power() {
int t;
foreach(x; enchantments) {t += x.basePower;}
foreach(x; globalEnchantments) {t += x.basePower;}
foreach(x; playerEnchantments) {t += x.basePower;}
return t;
}
int toughness();
//etc for a base class with expected functional hooks for combat, instants etc.
}
class Wurm : Card {
this() {
name = "Greater Wurm";
quote = "When the Wurm comes, all flee it's destruction";
basePower = 3;
baseToughness = 3;
}
//no tap or other abilities, left blank
}
class Beetle : Card {
Card original;
this(Card target) {
description = "The target card becomes a 0/1 indestructible beetle";
types="Green,Insect,Indestructible,Enchantment";
//code to swap original and target
}
~this() { //unswap }
override int power(){return 0;}
override int toughness(){return 1;}
}
class Sword : Card {
this() {
name="Soldier's sword";
description = "Enchanted creature gets +2/0";
types="Enchantment,Equipment,Colorless";
basePower = 2;
}
this(Card target) {
target.enchantments ~= this;
}
}
Here you have a base card to work with, a monster, enchantment and an override.