Monday, July 31, 2017

java - How should I implement card effects in a card game?


I've been trying to program a video game adaptation of the popular trading card game "Magic: The Gathering". If you've played MTG before, you'll know most cards have an effect, which is activated at a certain time, usually when it's played. But I'm unsure how to implement effects into my game.


I'm thinking of creating a method that assigns a card its effect when it's played based on the card's name, but that doesn't really work when a card's effect isn't supposed to be activated when it's played, like in the case of Deathrattle cards, or when it's a continuous effect. I've thought of creating a thread for each effect which activates it whenever needed, but... that's a LOT of unique threads. I haven't found any similar java programs anywhere, so I wanna ask here. How do you think card effects should be handled?




Answer



Threads would definitely be overkill here. I would use event listeners.


First, make an ICommand interface. (The param is so that you can optionally pass data to your command)


public interface ICommand{
public void execute(Object param);
}

Then make sure you clearly define every scenario in which a card will activate and create a ICommand variable in your Card class essentially creating a "slot" for each event type.


//Card class
ICommand onDeathrattleCommand;

ICommand onCardPlayedCommand;
//... other event types

When you create each card type, you initialize the appropriate event slots


Card deathrattleCard = new Card();
deathrattleCard.onDeathrattleCommand= new ICommand(){
public void execute(Object param){
foreach(Card opponentCard: opponentsCards){
opponentCard.applyDamage(6);
}

}
};

Then trigger these events at the appropriate time


//Card class
public void onPlayed()
{
if(onCardPlayedCommand != null){
onCardPlayedCommand.execute(null);
}

}

public void applyDamage(int damage)
{
hp -= damage;
if(hp <= 0 && onDeathrattleCommand != null){
onDeathrattleCommand.execute(null);
}
}

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...