Sunday, September 13, 2015

c# - Design Pattern for card game objects


In my game, I will have more than 100 types of cards,
and before the actual game, player can select 6 of them and will be shown as 6 buttons on the scene.
The card have its own ID, card name, and a 3D game Object prefab, and have a function call perfromCardAction which performs different actions.



public class cardA:cardInterface {
private int ID;
private string cardName;
private Texture2D cardImage;
private GameObject card3DObject;

...Constructor...

private override void prefromCardAction(){
...do Card A action...

}
}

A script cardManager should get the 6 object player selected and stored in an array.
And set the button's Image as card's 2D image.
when the button is click, that card's prefromCardAction should be called.


So my main quesstions are:
What pattern should I used so that easier manage my cards objects?
I believe I should use Factory so that I can do something like:


selectedCardArray[0]=CardFactory.createCard("CardA");


If yes, I would like to ask:
How should I code all my card class (cardA, cardB, cardC...)?
separate into different c# script and implement cardInterface and override the perfromCardAction?



Answer



I 'll try this aproach: I'm lazy so I included the factory inside the class card. I suggest using delegates to forge the behaviour of each card type, and a big and maybe brute, swith case inside the factory method (createCard).


public class card{
private int ID;
private string cardName;//getters setters?
private Texture2D cardImage;//getters setters?

private GameObject card3DObject;//getters setters?

...Constructor...

public delegate void theFuncPrototype();
private theFuncPrototype theFunc = {return;} ; //initialize?
public doAction()
{
this.theFunc();
}



// define all actions
private static actionCardA(){
//...
}
private static actionCardB(){
//...
}
//...


public static createCard(string cardType){
switch (cardType)
{
case "CardA":
card N = new card(....);
N.theFunc = actionCardA;
return N;
case "CardB":
card N = new card(....);

N.theFunc = actionCardB;
return N;
//...
default:
//... manage wrong cardType?
}
}

}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...