So, I am writing an rpg java game and decided to use custom events to simplify communication between the two classes. First I wrote "enemyDeathEvent" to let the player know if the enemy has died.
First I made my EnemyListener:
public interface EnemyListener {
public void playerDeathEvent(EnemyEvent e);
}
After that, I created the EnemyEvent class:
public class EnemyEvent {
private Enemy enemy;
public EnemyEvent(Enemy enemy) {
this.enemy = enemy;
}
public Enemy getSource() {
return enemy;
}
}
Then I create an Enemy class:
public class Enemy {
private boolean dead;
private Set<EnemyListener> listeners;
public Enemy() {
listeners = new HashSet<EnemyListener>();
}
public void update() {
if(health <= 0) dead = true;
if(dead) fireDeathEvent();
}
protecd synchronized void fireDeathEvent() {
EnemyEvent e = new EnemyEvent(this);
for(EnemyListener listener : listeners) {
listeners.enemyDeathEvent(e);
}
}
public void addEnemyListener(EnemyListener listener) {
listeners.add(listener);
}
}
Finally, when implementing an EnemyListener to a player:
public class Player implements EnemyListener {
@Override
public void enemyDeathEvent(EnemyEvent e) {
System.out.println(e.getSource().getName() + " died!");
}
}
So, when the enemy dies, the enemyDeathEvent () method from my class will be called . everything works fine , but my actual problem is that the game calls this method more than once . the reason is because my update () method is connected to a thread that updates the physics of the game, etc. 30 times per second.
@Override
public void run() {
while(gameRunning) {
update();
render();
try {
Thread.sleep(1000/30);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
, : , ?
!