I'm new to C# so I'm making a Snake Game to learn. I created an object of a snake which contains an array of objects called pieces. So the pieces make up the snake. I'm trying to change the first piece's x value by 1 in order move the first piece one unit to the right. The problem is that when I change the first piece's x value by 1, the second piece's x value also changes by 1. So myPiece[1].x = 6 and myPiece[2].x = 6 even though I only increased the first one's value. How can I make it so I can change the value of each individual piece without it changing the rest of the piece's values?
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;
}
}
thePieceis a poor choice for a class name. Same withtheSnake.