2016-10-06 38 views
1

我将使用我的具体用例来描述我的问题,但考虑到可能有其他应用程序想要根据某些默认值创建子类,它应该更广泛适用。这并不意味着成为“为我做作业”的问题。通过C#中的子类创建特定的类实例

我目前正在研究一个简单的俄罗斯方块游戏,我已经将我的游戏场定义为一个填充了bools的二维数组。我在一个类的Grid中添加了函数并分离了我的代码。我开发了一个函数,让我检查是否可以在某个位置添加另一个Grid,以检查Tetromino是否可以移动到某个位置。 (不是两个bools在一个位置上都是如此)

由于tetrominos(也是网格)具有预定义的形状和大小,因此只需创建一次每个形状,然后我可以将当​​前的下降块设置为那个预定义的tetromino可以按照我的意愿操作。

现在我知道了初始化这些预定义形状的两种方法:在初始化程序中的Tetris主类中启动它们,其中我为每个tetromino调用一次Grid(Columns,Rows)并手动将正确的坐标设置为true,或者在Grid类中创建第二个构造函数,该构造函数接受char(tetromino名称L,J,S,Z,T,X,I),并使用我已经构建的其他构造函数初始化3x3或4x4网格,然后手动设置正确的坐标再次为真。

这两种方法都给这些感觉难看的类增加了混乱。我希望有可能使用一个子类,从技术上考虑tetriminos是特定类型的网格

现在在子类只要我能找到也只能通过对被给予该子类的构造函数,像这样的默认参数或参数的构造函数:

class Grid 
{ 
    bool[,] grid; 

    public Grid(int x, int y) 
    { 
     // Creates grid, fills it with bools. 
    } 
} 

class Block : Grid 
{ 
    public Block(char blockShape, int x, int y) : base(x, y) 
    { 
     // Add additional logic here. 
    } 
} 

现在,这需要我传球在tetromino的尺寸,这感觉很奇怪,因为这将被预先设定。我更希望是沿着这些路线的东西:

class Block : Grid 
{ 
    public Block(string blockShape) 
    { 
     if ("IX".Contains(blockShape)) 
     { 
      this = new Grid(4, 4); 
      // Add additional logic here. 
     } 
     if ("JLSZT".Contains(blockShape)) 
     { 
      this = new Grid(3, 3); 
      // Add additional logic here. 
     } 
    } 
} 

是沿着这些线路可能的东西吗?如果是这样,那该怎么办?如果没有,是否有一个干净的替代解决方案,不会混乱我的Grid或Tetris类?我应该做其他事吗?

+0

Tetrominos - 哇,这是一个字! –

回答

0

我只是使用静态只读字段。 Tetrominos是不可改变的,你只需要初始化它们一次,并根据需要多次重复使用它们。

此外,我不太相信tetrominos派生自Grid。对我来说,它们在概念上是非常不同的东西;前者是预设的不可变块,后者是动态变化的竞技场。我不会混淆这两个因素。我想创建一个特定Tetromino类:

public class Tetromino 
{ 
    public static readonly Tetromino J = new Tetromino(new[,] { { false, false, true }, .... }); 
    public static readonly Tetromino L = new Terromino(new[,] { { true, false, false } .... }); 
    //and so on... 

    private readonly bool[,] grid; 
    private Tetromino(bool[,] shape) //disallow any other Terronimos from being built. 
    { 
     this.shape = shape; 
     Width = shape.GetLength(0); 
     Height = shape.GetLength(1); 
    } 

    public int Height { get; } 
    public int Width { get; } 
    public bool this[int row, int col] => shape[row, col]; 
} 

现在你TetrisGrid类中你会用Tetromino的工作而无需关心什么形状他们真的是。要产生一个特定的,你只需使用相应的领域; myPlayingGrid.Add(Tetromino.J)

+0

谢谢,我想我会为此尝试在init中实例化该类。它确实应该将代码转移到一个单独的文件中,这最终是我所追求的。我只是希望它可以更整洁。 为tetrominos使用网格类的原因是我简化了;网格存储节点,而不是布尔,它们也包含块的颜色。这将允许我为网格物体创建一个函数,这会让我在实​​际放置网格物体之前在特定位置上绘制tetromino。以及允许旋转tetromino的克隆。 –

相关问题