Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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?
Posted
Updated 23-Apr-17 22:13pm

1 solution

You should iterate a copy of the list while deleting elements; see 5. Data Structures — Python 3.4.5 documentation[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900