Slick2D-Beginner-Logic Problem

Hey together,

I just started to try to build something with the Slick-API.
As I faced some problems, I won´t get the solution for those two:

I have a Player (me) represented with a green Circle and 1-10 red Circles, which are supposed to be the Enemies.
The Enemy-Circles are “attracted” by the Player and come closer. Now I wanted the Player-Circle move to the closest
Enemy-Circle. And after “killing” this one, moving to the next-closest.
My idea goes like this (and it works sometimes), but after “killing” all Enemy-Circles except the last one my Player-Circle stops.
Also it sometimes does crazy things.
How do I fix this? Any suggestions?

for (int e = 0; e < enemies.size(); e++) {
				for (int j = 1; j < enemies.size(); j++) {
					//Nächsten Enemy herausfinden
					//X+Y
					if (Math.abs(actX - actXEn[e]) > Math.abs(actX - actXEn[j])) {

						prefX = actXEn[j];
						player1.move(player1, WIDTH, HEIGHT, delta, prefX, prefY);
					}
					if (Math.abs(actX - actXEn[e]) < Math.abs(actX - actXEn[j])) {

						prefX = actXEn[e];
						player1.move(player1, WIDTH, HEIGHT, delta, prefX, prefY);
					}
					if (Math.abs(actY - actYEn[e]) > Math.abs(actY - actYEn[j])) {

						prefY = actYEn[j];
						player1.move(player1, WIDTH, HEIGHT, delta, prefX, prefY);
					}
					if (Math.abs(actY - actYEn[e]) < Math.abs(actY - actYEn[j])) {

						prefY = actYEn[e];
						player1.move(player1, WIDTH, HEIGHT, delta, prefX, prefY);
					}
				} 

			}
			actX = (int) player1.getShape().getX();
			actY = (int) player1.getShape().getY();
		}

A general problem/question. How do I build-in something like another window in my actual playing-panel. I need something to
place new Circles, while in-game.

Thank you so much!

If you are trying to find the enemy which is nearest to your player, a single loop suffices.
Pseudo-code:


Player player = ...;
Enemy[] enemies = ...;
float minDistanceSqr = Float.POSITIVE_INFINITY;
Enemy nearestEnemy = null;
for (Enemy enemy : enemies) { // <- find nearest enemy
  float dx = enemy.position.x - player.position.x;
  float dy = enemy.position.y - player.position.y;
  float distanceSqr = dx * dx + dy * dy;
  if (distanceSqr < minDistanceSqr) { // <- new nearest enemy found
    minDistanceSqr = distanceSqr;
    nearestEnemy = enemy;
  }
}
// Here you know the nearestEnemy (if != null) and can do 
// whatever you want with it, such as moving the player towards it.

for (int j = 1; j < enemies.size(); j++) {

It stops at the last one, ignores the first one.

for (int j = 0; j < enemies.size(); j++) {

Thank You!
Works great :slight_smile: