I am working on a side scroller GUI game in Java. I have many kinds of enemies whose AIs run off Swing timers. As I understand it, Swing timers are kind of resource intensive, yet I still want my enemies to move around at different intervals. Is there a more efficient way to run things than using a different Swing timer for each kind of enemy?
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
A better way to solve this problems is to keep a list of enemies that exist on the screen, every time you render the next screen your main render loop should decided weather it should call any of the methods on the Enemy object or not.
public interface Enemy {
public void doNextThing();
}
public class TimedEnemy implements Enemy {
private long lastExecute;
private Enemy enemy;
private long threshHold;
public TimedEnemy(Enemy enemy, long threshold)
{
this.lastExecute = System.currentTimeMills();
this.enemy = enemy;
this.threshold = threshold;
}
public void doNextThing()
{
long duration = System.currentTimeMills() - lastExecute;
if( duration >= threshold) {
lastExecute = System.currentTimeMills();
this.enemy.doNextThing();
}
}
}
// main Render Loop
List<Enemy> enemies = new ArrayList<Enemy>();
TimedEnemy easy = new TimedEnemy(new EasyEnemy(),1000);
TimedEnemy hard = new TimeEnemy(new HardBadGuyEnemy(),100);
TimedEnemy boss = new TimeEnemy(new VeryBadBossEnemy(),50);
enemies.add(easy);
enemies.add(hard);
enemies.add(boss);
for( Enemy enemy : enemies) {
enemy.doNextThing():
}
If you really need to have every enemy AI run on its own thread then you need to use a TaskExecutor features of Java 5, with the Futures concept. Although running each AI on separate threads means that you have to be careful with thread synchronization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With