Java-Gaming.org    
Featured games (78)
games approved by the League of Dukes
Games in Showcase (426)
Games in Android Showcase (89)
games submitted by our members
Games in WIP (466)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Pausing Multiple Threads  (Read 1557 times)
0 Members and 1 Guest are viewing this topic.
Offline ReBirth
« Posted 2011-01-29 13:51:49 »

Hello. First I'm sorry if my english sounds weird. I'm creating a small animation. There are multiple balls "bouncing" on Frame and if any of them hits a placed special ball, it will grow big and become another special ball (which means any of the rest ball can be special too by hitting any of two special things and repeat again). However a special ball's lifespan is only 3 seconds. The Ball class extends Thread so it can call sleep(3000) and vanished after done. Ball isn't the main class.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
class Ball extends Thread{
public void run(){
         try{
            size = 100;
            isSpecial = true;
            this.sleep(3000);
            isDone = true; //tell main class to remove this "ball"
        }
         catch (InterruptedException e){
            System.err.println(e);
         }
      }
}


The main class puts every balls in an ArrayList. Main class uses Gudradrain's template. Now I want to include Pause feature. When paused the canvas will draw another image and doesnt call update() method. The problem is the sleep(3000) on every ball is still counting so when we back to the animation, all special balls suddenly disappear. How to make all special balls sleep only on non-paused state? in other word, pause the ball's sleep when enter pause state.

Thanks  Cheesy

Offline zoto

Senior Member


Medals: 4



« Reply #1 - Posted 2011-01-29 15:21:49 »

Don't use threads for this type of thing.
To use the template you linked to, create another class that extends his Game class and overwrite the update and render functions with empty functions.

Then create your ball class and just give it 2 functions to start off with update(int) and render(Graphics2D).

Now create the ArrayList or whatever collection you want to use of Balls like you already do, possibly in your game class constructor.

Now fill in the update and render functions in your game class with a loop that iterates over the array of balls and calls the appropriate function.

Now to add pause just put the update loop in a conditional block.
It should look something like
1  
2  
3  
4  
5  
6  
protected void update(int deltaTime){
  if( !paused ){
    for(Ball ball: balls)
      ball.update(deltaTime);
  }
}
Offline ReBirth
« Reply #2 - Posted 2011-01-29 16:31:57 »

Now to add pause just put the update loop in a conditional block.
It should look something like
1  
2  
3  
4  
5  
6  
protected void update(int deltaTime){
  if( !paused ){
    for(Ball ball: balls)
      ball.update(deltaTime);
  }
}


my current code goes like that with update() method updating position of the ball then checking for collision where if yes, start the 3seconds countdown and vanished. if no, nothing happen (still 'common' ball bouncing and waitting chance to hit the special). can you please give example code how the ball class wait for 3seconds before vanished but, that wait can be paused and resumed?

the rest as Game class and render() are already same approach like you said Cheesy

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline zoto

Senior Member


Medals: 4



« Reply #3 - Posted 2011-01-29 18:14:40 »

One way to have the ball vanish 3seconds after it is hit is to add a boolean and an int to the Ball class. Name the boolean something like fadeOut and the int fadeTimer.

Add some functions to the ball like this:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
private final int THREE_SECONDS = 3000;

public void fade(){
  fadeOut = true;
  fadeTimer = THREE_SECONDS;
}

protected void update(int delta){
  if( fadeOut ){
    fadeTimer -= delta;
    alive = fadeTimer > 0;
  }
}

protected void render(Graphics2D g){
  if( !alive )
    return;
  // draw as normal
}

Because update isn't called when the game is paused, the ball doesn't fade while paused.
Offline ReBirth
« Reply #4 - Posted 2011-01-30 04:29:42 »

@zoto:
so I just need to call fade() when the collision is detected and let the update() method to start counting down by decrement. But in my sight, delta is always changing depends on how long time needed to update, sleep and render (based on template). how about the accuracy so it can vanish on exactly 3scnds?

anyway thanks for above solution. I try it Smiley

Offline philfrei
« Reply #5 - Posted 2011-01-30 04:52:01 »

@zoto:
so I just need to call fade() when the collision is detected and let the update() method to start counting down by decrement. But in my sight, delta is always changing depends on how long time needed to update, sleep and render (based on template). how about the accuracy so it can vanish on exactly 3scnds?

anyway thanks for above solution. I try it Smiley

Might be a good place to use a Timer to run the gameloop. Or, build in some controls to the gameloop so that the loop time remains steady.

The delta variable is how many milliseconds have passed since the last update.
Ah...in that case then my suggestions on using the Timer are moot.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline zoto

Senior Member


Medals: 4



« Reply #6 - Posted 2011-01-30 13:09:41 »

Quote
so I just need to call fade() when the collision is detected and let the update() method to start counting down by decrement.
Yes, you also might want to check fadeOut in your collision detection so you can ignore fading circles.

Quote
But in my sight, delta is always changing depends on how long time needed to update, sleep and render (based on template). how about the accuracy so it can vanish on exactly 3scnds?
The delta variable is how many milliseconds have passed since the last update.
The counter will go a few milliseconds over 3 seconds depending how well the game is running, probably safe to ignore.
 
Offline ReBirth
« Reply #7 - Posted 2011-01-31 02:57:21 »

Quote
The delta variable is how many milliseconds have passed since the last update.
The counter will go a few milliseconds over 3 seconds depending how well the game is running, probably safe to ignore.

On small amount of balls it can be ignored but when I tried with 100 balls even I could sense the difference of fading time from 3scnds Smiley it can be fixed if I turn off the AA (less update time) but player also can trigger this AA so time of update can be changed anytime. Should I remove this AA although the circles will look rough? :|

When on applet (java webstart), if the page lose focus (user see other window or tab), do all threads from the applet get paused automaticly or not?

Offline zoto

Senior Member


Medals: 4



« Reply #8 - Posted 2011-01-31 14:37:13 »

Quote
On small amount of balls it can be ignored but when I tried with 100 balls even I could sense the difference of fading time from 3scnds Smiley it can be fixed if I turn off the AA (less update time)
That sounds promising. Just a guess because I can't see your code but is your ball draw function just drawing an image or are you using Graphics2D.draw* or Graphics2D.fill*?
If you are not using an image I would advise you switch to either loading an image or draw it once in your code and reuse it.

The program jvisualvm comes with java and is very useful for debugging performance issues.

Quote
but player also can trigger this AA so time of update can be changed anytime.
No code run on the client is safe from tampering.

Quote
Should I remove this AA although the circles will look rough? :|
I wouldn't give up so fast, figure out what you want the computer to do then figure out how to make it do that.

Quote
When on applet (java webstart), if the page lose focus (user see other window or tab), do all threads from the applet get paused automaticly or not?
This is something that has to be coded in, looking over the template it isn't in there. My first place to look for java help is the JavaDoc.
You would probably just implement FocusListener on your game class,
add this line to the constructor,
1  
canvas.addFocusListener( this );

and add something like this to the game class:
1  
2  
3  
4  
5  
6  
7  
void focusLost(FocusEvent e){
  paused = true;
}

void focusGained(FocusEvent e){
  paused = false;
}
Offline ReBirth
« Reply #9 - Posted 2011-02-02 14:01:13 »

Quote
That sounds promising. Just a guess because I can't see your code but is your ball draw function just drawing an image or are you using Graphics2D.draw* or Graphics2D.fill*?
I'm using Graphics2D.fillRect() because I only need circle.

Quote
If you are not using an image I would advise you switch to either loading an image or draw it once in your code and reuse it.
Sorry first but I really dont understand about "draw once". They're moving so they just need to be drawn every update right?

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline zoto

Senior Member


Medals: 4



« Reply #10 - Posted 2011-02-02 15:07:15 »

Quote
Sorry first but I really dont understand about "draw once". They're moving so they just need to be drawn every update right?
That was bad wording on my part.
What I was trying to explain is that Graphics2D.drawImage will perform better than a series of drawing commands. When I said draw once what I really meant to say was create the ball image once.

if that's not clear or you don't know how to do it maybe post your current Ball class.
Offline ReBirth
« Reply #11 - Posted 2011-02-04 04:45:51 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
class Ball extends Thread{

      private int x, y, dx, dy, value, size = 10;
      private Color color;
      private boolean die = false, idle = false;

      public Ball(){
         Random random = new Random();

         x = (int)(WIDTH * random.nextDouble());
         y = (int)(HEIGHT * random.nextDouble());
         //speed = 3
        dx = ((int)(3 * random.nextDouble()) - 1) * 3;
         dy = ((int)(3 * random.nextDouble()) - 1) * 3;
         if (dx == 0) dx = 3;
         if (dy == 0) dy = 3;

         color = new Color((int)(170 * random.nextDouble()) + 80,
            (int)(170 * random.nextDouble()) + 80,
            (int)(170 * random.nextDouble()) + 80);
      }

      public void setValue(int v){
         this.value = v;
      }

      public void updatePos(){
         this.x += dx;
         this.y += dy;
         if (x < 0){
            x = 0;
            dx = -dx;
         }
         if (x + size > WIDTH){
            x = WIDTH - size;
            dx = -dx;
         }
         if (y < 0){
            y = 0;
            dy = -dy;
         }
         if (y + size > HEIGHT){
            y = HEIGHT - size;
            dy = -dy;
         }
      }

      public void updateDraw(Graphics2D g){
         g.setColor(color);
         g.fillOval(x, y, size, size);
         if (isAlive()){
            g.setColor(Color.white);
            g.drawString(String.valueOf(value), x + 35, y + 55);
         }
      }

      public boolean checkColl(){
         int calc, dx, dy;
         boolean ret = false;
         if (big.size() > 0){
            for (Point bg : big){
               dx = (int)Math.abs(bg.getX() - x);
               dy = (int)Math.abs(bg.getY() - y);
               if (dx > RADIUS || dy > RADIUS){
                  continue;
               }else{
                  calc = (int)(Math.pow((dx - 5), 2) + Math.pow((dy - 5), 2));
                  if (calc <= RADIUS){
                     ret = true;
                     break;
                  }
               }
            }
         }
         return ret;
      }

      public void run(){
         try{
            size = 100;
            x -= 45;
            y -= 45;
            idle = true;
            this.sleep(3000);
            die = true;
         }
         catch (InterruptedException e){
            System.err.println("ball "+e);
         }
      }
   }

this is my current Ball class which work well by extending Thread (ofc no pause function until here). Dont mind the value variabel and method regarding it, they're optional.

Ball size defaultly is 10 and 100 when become big (turn into special ball). I pass the Graphics2D to each Ball while on render() loop so each Ball can draw itself regarding their positions and color. checkColl() detects for collision to special balls. I save all special balls by their (x,y) of center only, not whole Ball class. That's why I have ArrayList<Point> "big" to store all special ball but coordinat of the center only.

I hope this will make clear everything. On game class nothing special there.

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (75 views)
2014-04-15 18:08:23

BurntPizza (68 views)
2014-04-15 03:46:01

UprightPath (80 views)
2014-04-14 17:39:50

UprightPath (65 views)
2014-04-14 17:35:47

Porlus (81 views)
2014-04-14 15:48:38

tom_mai78101 (105 views)
2014-04-10 04:04:31

BurntPizza (165 views)
2014-04-08 23:06:04

tom_mai78101 (261 views)
2014-04-05 13:34:39

trollwarrior1 (210 views)
2014-04-04 12:06:45

CJLetsGame (220 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!