Visual C#对象数组更改数组中的所有元素而不是一个元素

时间:2011-12-31 06:16:36

标签: c# arrays

我是C#的新手所以我正在制作一个蛇游戏来学习。我创建了一个蛇的对象,其中包含一个名为pieces的对象数组。所以这些碎片构成了蛇。我试图将第一个棋子的x值改为1,以便将第一个棋子的一个单位向右移动。问题是,当我将第一个棋子的x值改为1时,第二个棋子的x值也会改变1.所以myPiece [1] .x = 6和myPiece [2] .x = 6即使我只增加了第一个一个人的价值。我怎样才能这样做,这样我就可以改变每件作品的价值而不改变作品价值的其余部分?

class theSnake
{
    private int size;
    private thePiece[] myPieces=new thePiece[50];
    private int xDim;
    private int yDim;


    public theSnake(int pxDim,int pyDim)
    {
        size = 1;
        xDim = pxDim;
        yDim = pyDim;
        for (int i = 1; i <= 49; i++)
        {
           myPieces[i] = new thePiece();
        }

        myPieces[1].setX(xDim/2);  //sets the starting of the snake in the center of the field
        myPieces[1].setY(yDim/2);
        myPieces[1].setDir(3);
    }

    public void move()
    {

         //the pieces trade positions with the positions in front of it
        //the pieces travel backwards instead of forwards so there is no gap created
        for (int i = size; i >= 2; i--)
        {
            myPieces[i] = myPieces[i-1];
        }

        //moves leading snake based on direction given
        switch (myPieces[1].getDir())
        {
            case 1:
                myPieces[1].setY(myPieces[1].getY() + 1);
                break;
            case 2:
                myPieces[1].setY(myPieces[1].getY() - 1);
                break;
            case 3:
                myPieces[1].setX(myPieces[1].getX() + 1);
                break;
            case 4:
                myPieces[1].setX(myPieces[1].getX() - 1);
                break;
        }

    }

class thePiece
{
    private int x;
    private int y;
    private int direction;
    //north = 1 south = 2 east = 3 west =4
    public thePiece()
    {
        x = 0;
        y = 0;
        direction = 1;
    }

}

2 个答案:

答案 0 :(得分:2)

for (int i = size; i >= 2; i--) 
{ 
    myPieces[i] = myPieces[i-1]; 
} 

因为myPieces[2]指向myPieces[1],换句话说,myPieces[2]myPieces[1]是同一个对象。现在,myPieces[2]引用了原始myPieces[3]对象。

如果要分配值,可以使用以下代码

 for (int i = size; i >= 2; i--) 
    { 
        myPieces[i].x = myPieces[i-1].x; 
        myPieces[i].y = myPieces[i-1].y; 
        myPieces[i].direction = myPieces[i-1].direction; 
    } 

答案 1 :(得分:0)

您的问题是您没有正确地交换数组中的对象:

更改以下内容:

   for (int i = size; i >= 2; i--)
    {
        myPieces[i] = myPieces[i-1];
    }

如下所示(如果我不能正确理解你的逻辑,可能需要进行一些小调整):

   for (int i = size; i >= 2; i--)
    {
        // Save a reference to the piece that will be written over
        var savePiece = myPieces[i];
        // Move the previous piece
        myPieces[i] = myPieces[i-1];
        // Now move the saved piece to the previous position
        myPieces[i-1] = savePiece;
    }