问题描述
我最近正在设计一款手机游戏,当我设计技能系统的一部分时我遇到了问题。假设代码:
类士兵:
{
list< skill>技能;
RemoveSkill(技能){技能。移除(技能)}
OnNewTurn(){技能技能:skill.OnNewTurn()}
}
等级技能
{
转= 1;
ownerSoldier;
OnNewTurn()
{
--turn;
if(转< = 0)
{ownerSoldier.Remove(self);
删除自己;
}
}
你可以看到,当玩家获得新的转弯时,也许技能应该从士兵的列表中删除,但是列表正在遍历,删除技能会使遍历迭代器无效。我使用python,但是我想在没有特定语言的情况下讨论这个问题。实际上我通常有这个问题....请原谅我的英文不好,我是中国人。请帮帮我,谢谢你们:)
我的尝试:
我有一个解决这个问题的方法:
级士兵:
{
list< skill>技能;
RemoveSkill(技能){skills.remove(技能); }
OnNewTurn(){技能技能:skill.OnNewTurn();
skills.remove(lambda技能:返回技能.IsInvalid());
}
}
class Skill
{
...
IsInvalid(){return turn< = 0;}
}
它可以工作,但我认为它不够优雅。因为技能移除时的控制力应属于自己。如果我这样做,控制权属于另一类。我该怎样解决这个问题?我应该改变设计模式吗? ?
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?
这篇关于有关删除元素和遍历同时出现的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!