我的介绍:
我写了个棋子类Chessman,一个棋盘类chessboard,这个棋盘上可以放81个棋子.我的疑问:
如果我想显示3个棋子,是每个棋子都new一个不同Chessman对象?(ChessmanA,ChessmanB,ChessmanC)
还是new一个Chessman对象,这个对象产生三个棋子? 将来我还得对某一个棋子做别的操作,比如销毁(吃).
我的思考:
如果是每个棋子作为一个独立的Chessman类的实例,这样通过不同的"对象名."就可以做别的操作了,但81个棋子,就是81个对象,在对象声明的时候岂不是:private Chessman ChessmanAA;
private Chessman ChessmanAB;
private Chessman ChessmanAC;
......这看着也太难看点了吧?
如果是作为Chessman类型的二维数组,每个元素都是Chessman类的一个实例(一个棋子)
数组声明的时候得 private Chessman [,]ArrChessman
数组元素还得声明 private Chessman ArrChessman[0,0]private Chessman [,] ArrChessman;public void Fun()
{
Chessman [,] ArrChessman = new Chessman[9,9];
for(int i = 0; i<9; i++)
{
for(int j = 0; j<9; j++)
{
ArrChessman[i,j] = new Chessman()
//初始化Chessman类的实例
//为了能在别的地方使用ArrChessman[i,j],还得在Fun()外边声明每个实例
//private Chessman ArrChessman[0,0]  这样?
//private Chessman ArrChessman[0,1]  这样?这行吗这个?
//private Chessman ArrChessman[... , ...] 
}
}
}

解决方案 »

  1.   

    你这棋子能移动么?好像不太对,不应该有81个棋子,所以你不需要初始赋值,只有在用户放置棋子后再在对应位置设置一个对象,然后在用户移动棋子时,再改动,譬如class Board
    {
    private Chessman [,] ArrChessman;public Board()
    {
     ArrChessman = new Chessman[9,9];
    }public void AddChessAt(int x,int y)
    {
      if (ArrChessman[x,y] == null)
      {
    Chessman c= new Chessman();
    //....做些初始化
    ArrChessman[x,y] = c;
    //...重画该位置
      }
    }
    public void KillChessAt(int x,int y)
    {
      if (ArrChessman[x,y] != null)
      {

    Chessman c= ArrChessman[x,y];
    //....处理这个棋子,譬如放到俘虏群里
    ArrChessman[x,y] = null;
    //...重画该位置
      }
    }public void MoveChess(int fromx, int fromy, int tox, int toy)
    {
      if (ArrChessman[fromx,fromy] != null && ArrChessman[tox,toy] == null)
      {

    Chessman c= ArrChessman[fromx,fromy];
    ArrChessman[fromx,fromy] = null;
    //....处理这个棋子,譬如放到俘虏群里
    ArrChessman[tox,toy] = c;
    //...重画该位置
      }
    }
      

  2.   

    不一定非要用类\对象来做.9X9的棋盘格,只需要9*9的2维数组,数组里每个元素4种状态分别是3种棋子和没有棋子.你说的初始化81个对象,其实只需要把数组清0.销毁某个棋子也是把数组对应元素设0(表示没有棋子),设计计个方法就行了.这样看来,设计一个class,里面有几个数组,几个方法就可以做完这些事.
      

  3.   

    C#里有泛型集合为什么不用? 可以用List<Chessman>来试试存储对象,这样效率会高点
      

  4.   

    我做过一个小型的棋类游戏的程序。要在棋子类中存放棋子的坐标,每个棋子根据这个信息在棋盘中绘制自己。要有一个和棋盘一样的棋子数组,有棋子的地方存放棋子对象,没有的就是null,移动棋子时改变数组和棋子的坐标,再重绘整个棋盘。
    吃子时就设成null,再重绘。