I want to move character on a 2D board. The board has a finite width and height (e.g. six columns, six rows). Let's say a piece is on the board at 0,0. I want to let it randomly move in a direction. However, considering it's at 0,0 it can't move up or left, and so on. I thought the best way to deal with this would be to start with all the movement options open, and then remove the ones that are impossible.
Here's what I got so far. xPosition
and yPosition
are the original positions of the element (defined in the constructor).
public void move() {
int[][] world = new int[6][6];
int worldRows = world[0].length;
int worldCols = world.length;
Random randomInt = new Random();
List<Integer> directionOptions = Arrays.asList(1, 2, 3, 4);
/*
* 1 = move up 3 = move down
* 2 = move right 4 = move left
*/
// Entity is in left column
if (this.xPosition == 0) {
directionOptions.remove((Integer) 4);
}
// Entity is in right column
if (this.xPosition == worldCols) {
directionOptions.remove((Integer) 2);
}
// Entity is in top row
if (this.yPosition == 0) {
directionOptions.remove((Integer) 1);
}
// Entity is in bottom row
if (this.yPosition == worldRows) {
directionOptions.remove((Integer) 3);
}
int randomMove = directionOptions.get(randomInt.nextInt(directionOptions.size()));
switch(randomMove) {
// 1: Move up
case 1: this.yPosition = this.yPosition - 1;
break;
// 2: Move right
case 2: this.xPosition = this.xPosition + 1;
break;
// 3: Move down
case 3: this.yPosition = this.yPosition + 1;
break;
// 4: Move left
case 4: this.xPosition = this.xPosition - 1;
break;
}
}
But I when calling move on an entity (e.g. john.move()
) I get the following error:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
at java.util.AbstractCollection.remove(Unknown Source)
at Entity.move(Entity.java:48) // directionOptions.remove((Integer) 4);
at Game.main(Game.java:21) // john.move()
Which points to the contents of the first if-clause: directionOptions.remove((Integer) 4);
. What am I doing wrong? Why can't I remove an Integer from my Integer list?