Reputation: 3
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;
}
}
Upvotes: 0
Views: 701
Reputation: 371
for (int i = size; i >= 2; i--)
{
myPieces[i] = myPieces[i-1];
}
because myPieces[2]
point to myPieces[1]
, in an other word, myPieces[2]
and myPieces[1]
are the same object. the orignal myPieces[2]
object now is referenced by myPieces[3]
.
if you want to assign values, you can use following code
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;
}
Upvotes: 2
Reputation: 44931
Your issue is that you are not properly swapping the objects in the array:
Change the following:
for (int i = size; i >= 2; i--)
{
myPieces[i] = myPieces[i-1];
}
To something like the following (this may need minor tweaks if I didn't understand your logic correctly):
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;
}
Upvotes: 0