I've been thinking a lot about what could be the most efficient way to move an object in Java -- meaning "changing their coordinates (x and y) on a map". I have come up with the solution below. Considering I'm new at Java, I really like what I came up with. There's one problem though. As you can see there is a "don't move" option. Either an element moves 1 coordinate to the top, right, bottom or left, or it doesn't move at all. In theory all is good when all values are possible: each possibility has 20% chance of occurring. However, things turn bleak when an element is sitting in a corner: two possible directions will be removed, so there are only three options left. This means that the probability of "don't move" equals the others' probability, namely 33.33%. That's a lot. Chances are that for many subsequent turns, the element will just sit in its corner before probability dictates it moves out of that corner. That's why I want to add weighted probability to the choices.
I don't want to give "don't move" a high probability, but the others must be equally probable. I was thinking 22.5% chance per direction, except for "don't move" which would then have a 10% probability.
I think this is a good answer, but it isn't a duplicate, in the sense that I'm not looking for a generic example. I need an implementation that doesn't use that list to add possible values and weight, those values should be hardcoded. Additionally, I'm not entirely sure how that answer works, so I'd like the code to be annotated well!
public void move(int worldWidth, int worldHeight) {
Random randomInt = new Random();
List<Integer> directionOptions = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3, 4));
/*
* 1 = move up 3 = move down
* 2 = move right 4 = move left
* 0 = don't move
*/
// Entity is in left column
if (this.xPosition == 0) {
directionOptions.remove((Integer) 4);
}
// Or entity is in right column
else if (this.xPosition == worldWidth) {
directionOptions.remove((Integer) 2);
}
// Entity is in top row
if (this.yPosition == 0) {
directionOptions.remove((Integer) 1);
}
// Or entity is in bottom row
else if (this.yPosition == worldHeight) {
directionOptions.remove((Integer) 3);
}
int randomMove = directionOptions.get(randomInt.nextInt(directionOptions.size()));
switch(randomMove) {
// 0: Don't move
case 0: break;
// 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;
}
}
Aucun commentaire:
Enregistrer un commentaire