我正在做一些OO分析来计算游戏组件之间的关系,这样我就可以设计类了。我将在C#结束。
需求
我的游戏包括:
棋子:积木、卡片、柜台
地点:栅格、堆栈
可能放置的碎片:
分析
然后我就糊涂了..。
每一件作品都有-一个地方,所以那里有一段关系。这是一对一的关系,因为每一件必须有一个,也只有一个地方。
但是,如何确保块只能在网格上运行,卡只能在堆栈上运行,而计数器只能在任意一个上运行?
提前感谢您的帮助。
发布于 2015-04-13 13:36:59
但是,如何确保块只能在网格上运行,卡只能在堆栈上运行,而计数器只能在任意一个上运行?
您可以利用泛型和泛型类型约束在编译时强制执行这些规则。
public interface IPiece<TPlace> where TPlace : IPlace
{
TPlace Place { get; }
void PlaceOn(TPlace place);
}
public class Block : IPiece<Grid>
{
private Grid _place;
public Grid Place
{
get { return _place; }
}
public void PlaceOn(Grid place)
{
_place = place;
}
}发布于 2015-04-14 00:13:14
人们经常声称您应该使用重于继承。考虑到这一点,我一直在玩弄这个想法,这就是我想出的:
class Grid
{ }
class Stack
{ }
abstract class Location
{
private Location() {}
public class GridLocation : Location
{
public Grid Grid { get; set; }
public int X { get; set; }
public int Y { get; set; }
}
public class StackLocation : Location
{
public Stack Stack { get; set; }
public int Position { get; set; }
}
}
abstract class Visual
{
}
class Block
{
public Visual Visual { get; set; }
public Location.GridLocation Location { get; set; }
}
class Card
{
public Visual Visual { get; set; }
public Location.StackLocation Location { get; set; }
}
class Counter
{
public Visual Visual { get; set; }
public Location Location { get; set; }
}
class Game
{
public IEnumerable<Block> Blocks { get; set; }
public IEnumerable<Card> Cards { get; set; }
public IEnumerable<Counter> Counters { get; set; }
public IEnumerable<Tuple<Location.StackLocation, Visual>> StackVisuals
{
get
{
var cardVisuals =
Cards.Select (c => Tuple.Create(c.Location, c.Visual));
var counterVisuals =
Counters.Select (c => Tuple.Create(c.Location, c.Visual))
.OfType<Tuple<Location.StackLocation, Visual>>();
return cardVisuals.Concat(counterVisuals).OrderBy (v => v.Item1.Position);
}
}
public IEnumerable<Tuple<Location.GridLocation, Visual>> GridVisuals
{
get
{
var blockVisuals =
Blocks.Select (b => Tuple.Create(b.Location, b.Visual));
var counterVisuals =
Counters.Select (c => Tuple.Create(c.Location, c.Visual))
.OfType<Tuple<Location.GridLocation, Visual>>();
return blockVisuals.Concat(counterVisuals).OrderBy (v => new { v.Item1.X, v.Item1.Y });
}
}
}我在示例中使用了占位符Visual类,以说明在需要时如何使用特定的位置类型统一实体(例如,StackVisuals和GridVisuals)。
https://stackoverflow.com/questions/29606582
复制相似问题