也许在某些事件处理程序中,您想决定施放哪个咒语。也许您可以从这个咒语施放器开始:
public class Caster
{
private readonly ICastable[] _spells;
private int _canCastAt;
public Caster(ICastable[] spells)
{
_spells = spells;
_canCastAt = -1;
}
public string GetNextSpellToCast(int currentTime)
{
if (currentTime < _canCastAt)
return null;
for (int i = 0; i < _spells.Length; i++)
{
int durationOfCast = _spells[i].AttemptCast(currentTime);
if (durationOfCast > 0)
{
_canCastAt = currentTime + durationOfCast;
return _spells[i].GetName();
}
}
return null;
}
}
施法者将会施放咒语:
public interface ICastable
{
string GetName();
int AttemptCast(int msCurrentTime);
}
您描述了一种特定类型的咒语:
public class ChanneledSpell : ICastable
{
private readonly string _name;
private readonly int _castDuration;
private readonly int _castCooldown;
private int _lastCast;
public ChanneledSpell(string name, int castDuration, int castCooldown)
{
Debug.Assert(castDuration < castCooldown);
_name = name;
_castDuration = castDuration;
_castCooldown = castCooldown;
_lastCast = -_castCooldown;
}
public string GetName()
{
return _name;
}
public int AttemptCast(int msCurrentTime)
{
if (msCurrentTime > _lastCast + _castCooldown)
{
_lastCast = msCurrentTime;
return _castDuration;
}
return 0;
}
}
我看到这篇文章被标记为C++,但我的答案是用C#编写的,虽然我只使用了C++中可用的语言结构,因此应该是一个简单的翻译。但我无法轻松地翻译一些测试内容。
[TestFixture]
public class SpellTest
{
[Test]
public void TestCanCastOnStartup()
{
var sut = new ChanneledSpell(Some.String(), Some.PositiveNonzeroInteger(), Some.PositiveNonzeroInteger());
int result = sut.AttemptCast(Some.PositiveNonzeroInteger());
Assert.IsTrue(CastWasMade(result));
}
[Test]
public void TestCantCastUntilCooldown()
{
int firstCast = Some.PositiveNonzeroInteger();
int duration = Some.PositiveNonzeroInteger();
int cooldown = duration + Some.PositiveNonzeroInteger();
var sut = new ChanneledSpell(Some.String(), duration, cooldown);
int ignored = sut.AttemptCast(firstCast);
int secondCastAttempt = sut.AttemptCast(firstCast + cooldown - 1);
int thirdCastAttempt = sut.AttemptCast(firstCast + cooldown + 1);
Assert.IsFalse(CastWasMade(secondCastAttempt));
Assert.IsTrue(CastWasMade(thirdCastAttempt));
}
[Test]
public void TestReportsTimeOnCast()
{
int duration = Some.PositiveNonzeroInteger();
int firstCastTime = Some.PositiveNonzeroInteger();
var sut = new ChanneledSpell(Some.String(), duration, Some.PositiveNonzeroInteger());
int firstCastAttempt = sut.AttemptCast(firstCastTime);
Assert.AreEqual(duration, firstCastAttempt);
}
private bool CastWasMade(int result)
{
return result > 0;
}
}