我正在开发一种轨道生成器(用于我未来的赛车游戏),它正在生成轨道。构建后,跟踪由游戏引擎处理等。 Track是元素的集合,可以是:
每个元素都有一个length属性,应该在构建track的元素时生成。元素依赖于之前生成的元素(在慢速之后快速转角有点奇怪)。
我第一次寻求“ifing”的解决方案:
public class ElementType
{
...
public double GenerateLength()
{
switch (m_TypeEnum)
{
case ElementTypeEnum.SlowSpeedCorner:
return Parameters.SlowCornerAvgLength+Generator.GetDeviation;
...
case ElementTypeEnum.LongStraight:
default:
return Parameters.LongStraightAvgLength + Generator.GetDeviation(Parameters.LongStraightLengthMaxDeviation);
}
}
...
public IList<ElementType> GetPossibleSuccessors()
{
switch (m_TypeEnum)
{
case ElementTypeEnum.SlowSpeedCorner:
return new List<ElementType>() { new ElementType(ElementTypeEnum.SlowSpeedCorner), new ElementType(ElementTypeEnum.ShortStraight), new ElementType(ElementTypeEnum.LongStraight) };
...
case ElementTypeEnum.LongStraight:
default:
return new List<ElementType>() { new ElementType(ElementTypeEnum.SlowSpeedCorner), new ElementType(ElementTypeEnum.MediumSpeedCorner), new ElementType(ElementTypeEnum.FastSpeedCorner) };
}
}
}
public enum ElementTypeEnum : int
{
LongStraight = 1,
SlowSpeedCorner = 2,
}
发电机基于方法:
public static TrackElement GenerateElement(TrackElement Predecessor)
{
ElementType type = SelectElementType(Predecessor);
double length = type.GenerateLength();
return new TrackElement(type, length);
}
private static ElementType SelectElementType(TrackElement Predecessor)
{
IList<ElementType> successors = Predecessor.Type.GetPossibleSuccessors();
int possibleSuccessors = successors.Count;
int selected = Generator.GetInt(possibleSuccessors);
return successors[selected];
}
但是正如你可以猜到的那样,在引擎中消耗它时这是一个戏剧 - 每个属性的结果都太多了“ifing”。所以我根据以下内容将元素移动到不同的类:
public abstract class TrackElement
{
public TrackElement(double Length)
{
m_length = Length;
}
protected abstract static double GenerateLength();
public sealed double Length
{
get
{
return m_length;
}
}
}
但是现在我使用提供的类构建轨道时遇到问题:
public static TrackElement GenerateElement(TrackElement Predecessor)
{
??? type = SelectElementType(Predecessor);
double length = type.GenerateLength();
return new ???(length);
}
当然我知道我不能这样做,因为GenerateLength是静态的,我只想起草我的问题。我怎样才能做到这一点?
答案 0 :(得分:0)
将轨道排序逻辑与构造逻辑分开;将其移至负责构建完整轨道的实体。然后让你的工厂有名的。
public abstract class TrackElementFactory
{
public abstract TrackElement CreateFastCurve();
public abstract TrackElement CreateLongStraight();
}
public class TrackArranger
{
public Track CreateAwesomeTrack()
{
var factory = //get from somewhere
var track = new Track();
track.Add(factory.CreateFastCurve());
track.Add(factory.CreateLongStraight());
....
return track;
}
}
此外,您可能更乐意对TrackElement抽象进行此更改。它允许您的实现更清洁。
public abstract class TrackElement
{
public abstract double Length
{
get;
}
}