I have an array with Coordinate objects. In the beginning, a for-loop assigns the values so that v(1] becomes v[0] (also what I want). Then I change v[0] independently but v(1] is now changing too. This is not what is suppose to happen. How can you solve this? Used input: direction = "R", width = 26, heigth = 26.(code under screenshot).
code:
package Snake;
import java.util.Random;
import java.util.Locale;
import java.util.Scanner;
import ui.Event;
import ui.SnakeUserInterface;
import ui.UserInterfaceFactory;
public class Snake {
int lengthOfSnake;
Coordinate[] snakePosition = new Coordinate[20];
Snake() {
lengthOfSnake = 2;
}
void initializeSnake() {
for(int i = 0; i< 20; i ) {
snakePosition[i] = new Coordinate();
}
snakePosition[0].x = 1;
snakePosition[0].y = 0;
}
void move(String direction, int width, int height) {
for(int i = lengthOfSnake - 1; i >0; i--) {
snakePosition[i].x = snakePosition[i-1].x;
snakePosition[i].y = snakePosition[i-1].y;
System.out.printf("index %d: %d.%d\n", i, snakePosition[i].x, snakePosition[i].y);
}
System.out.println();
if(direction.equals("R")) {
snakePosition[0].x = 1;
snakePosition[0].x = snakePosition[0].x % width;
}
else if(direction.equals("L")) {
snakePosition[0].x -= 1;
if(snakePosition[0].x ==- 1) {
snakePosition[0].x = width - 1;
}
}
else if(direction.equals("U")) {
snakePosition[0].y -= 1;
if(snakePosition[0].y ==- 1) {
snakePosition[0].y = height - 1;
}
}
else {
snakePosition[0].y = 1;
snakePosition[0].y =snakePosition[0].y % height;
}
for(int i = lengthOfSnake - 1; i >0; i--) {
System.out.printf("index %d: %d.%d\n", i, snakePosition[i].x, snakePosition[i].y);
}
System.out.print("end move method\n");
}
void growTail() {
lengthOfSnake ;
snakePosition[lengthOfSnake] = snakePosition[lengthOfSnake - 1];
}
boolean didSnakeEatItself() {
for(int i = 1; i < lengthOfSnake; i ) {
if((snakePosition[0].x == snakePosition[i].x) && (snakePosition[0].y == snakePosition[i].y)) {
return false;
}
}
return true;
}
}
CodePudding user response:
I assume that your snakePosition
array consists of objects like that:
public class SnakePosition {
public int x;
public int y;
public SnakePosition(int x, int y) {
this.x=x;
this.y=y;
}
public String toString() {
return "x=" x ",y=" y;
}
}
When you have to SnakePosition
objects like that:
var pos1 = new SnakePosition(1,1);
var pos2 = new SnakePosition(2,2);
and do the following assignments and object changes
pos1 = pos2;
pos1.x = 0;
your two objects pos1
and pos2
will be both x=0,y=2.
You can do the following and making a deep copy method:
public class SnakePosition {
..
public SnakePosition deepCopy() {
return new SnakePosition(this.x, this.y);
}
}
and use it like that:
for(int i = lengthOfSnake - 1; i >0; i--) {
snakePosition[i] = snakePosition[i-1].deepCopy();
}
Another positibility would be to directly copy the x
and y
values:
for(int i = lengthOfSnake - 1; i >0; i--) {
snakePosition[i].x = snakePosition[i-1].x;
snakePosition[i].y = snakePosition[i-1].y;
}