I am designing a mobile game recently,and I have a problem when I design the part of skill system.pseudo-code:
class Soldier:
{
list<skill> skills;
RemoveSkill(skill){ skills.remove(skill) }
OnNewTurn(){for skill in skills:skill.OnNewTurn()}
}
class Skill
{
turn = 1;
ownerSoldier;
OnNewTurn()
{
--turn;
if(turn <= 0)
{ ownerSoldier.Remove(self);
delete self;
}
}
as you can see, when player get a new turn, perhaps a skill should remove from the list in the soldier, but the list is being traversalling, to remove a skill will make the traversalling iterator invalid. I use python,but I want to discuss this question without a particular language.actually I usually have this problem....Excuse my bad English,I am a Chinese.Help me please,thank you guys :)
What I have tried:
I have a solution for this problem:
class Soldier:
{
list<skill> skills;
RemoveSkill(skill){ skills.remove(skill); }
OnNewTurn(){for skill in skills:skill.OnNewTurn();
skills.remove(lambda skill:return skill.IsInvalid());
}
}
class Skill
{
...
IsInvalid(){return turn <= 0;}
}
It can work,but I think it's not elegant enough.Because the control power in when the skills remove should belong to itself.If I do this,the control power belongs to the other class.How should I solve this problem?Should I change design pattern?