Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd running thread objects in to an arraylist
    primarykey
    data
    text
    <p>I am creating a small tank game using java. In that game, lifepacks and coin piles are generated at a random place on the game grid time to time. They both have a <strong>limited lifetime</strong> and <strong>after lifetime expires they are vanished from the field</strong>. When they visible on the grid, any tank can acquire them before vanish. And I want to keep the list of lifepack objects and coinpile objects in an <strong>ArrayList</strong> in order to access them by the game AI algorithm. I hope to implement the above concept as follows using simple java knowledge.</p> <p>Following is my LifePack class.CoinPile class behaves in a similar manner:</p> <pre><code>public class LifePack extends Thread{ public int healthBonus; public int lifetime; public String type; public Point location; public boolean visible; public LifePack(int x,int y,int lifetime){ location=new Point(x, y); this.lifetime=lifetime; this.type="health_pack"; this.visible=true; this.start(); } public void run(){ while(true){ if(this.lifetime&gt;0){ try{ Thread.sleep(1); if(lifetime%1000==0){ System.out.println("Life pack "+this.getId()+" will be disappeared in "+this.lifetime/1000+" s"); } this.lifetime--; } catch(Exception ex){ ex.printStackTrace(); } } else{ this.visible=false; this.interrupt(); break; } } System.out.println("Life pack visibility = "+this.visible); } } </code></pre> <p>I want to add the newly created LifePack Objects into an arraylist as follows:</p> <pre><code>public ArrayList&lt;LifePack&gt; lifePacks; lifePacks = new ArrayList&lt;LifePack&gt;(); lifePacks.add(new LifePack(x, y, lifeTime)); </code></pre> <p>Each time a new lifepack is created I add that lifepack object into the arraylist above. Once the lifepack's lifetime expires, I want to set the '<strong>visible</strong>' boolean variable in the above class to '<strong>false</strong>' so that I can check that variable for other purposes.</p> <p>But I don't get my desired output. Can I add running thread objects into an arraylist as above and keep the thread state running or Will I have to move to a different implementation? Please somebody help me to clear this out if there is a solution.</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload