how to call methods in java simultaneously? - java

I'm working on a simple 2D text-base game. So, I have 2 Player class thats fighting in a Arena class. I want to use them at the same time and modify their (position, hp, etc...)
For example: when program is running, Player1 move to x,y position, Player2 move to x,y position and then they have new position in Arena at the same time.
What's the best way to do this?

Don't conflate game time with CPU time. Just because players move at the same game time doesn't mean you need to have CPU threads executing concurrently. You just need a logic loop that simulates simultaneous movement.
For example, loop over all the players and check that their actions don't conflict with each other. If two players want to move to the same location, show an error. Otherwise, loop over them a second time and move them all to their new locations. Then redraw the scene. Even though you're updating the players one at a time in the second loop, the screen won't show the movements until the entire scene is repainted.

For this you must use thread. Here is an example of this:
public static void main(String[] args) {
new Thread() {
public void run() {
method1();
}
}.start();
new Thread() {
public void run() {
method2();
}
}.start();
//etc
//or, as kingdamian42 pointed out, if you use java8, use this
new Thread(() -> method1()).start();
new Thread(() -> method2()).start();}
here method one and two will be you players move.

Related

Pause game and add flashing text Java

I have this loop
while (true) {
game.update();
view.repaint();
Thread.sleep(DELAY);
}
In the game.update various components of the game have their position changed and those updates are reflected when the repaint() method is called on the view. The view extends JComponent and loops through the game objects and calls their print methods.
What I want to do is have a boolean called nextLevel in the game and if it's true Flash text on the screen for the player to notify them that they're going onto the next level. Maybe flash 4-5 times. Then continue the game.
Is this possible? I have been playing around with Thead.Sleep() but this only seems to pause the displaying and in the background the game is still going on.
Any ideas on how to do this?
Maybe you want to avoid threading by using a Timer object.
an example like that could be
int flashTimer = 0;
if(nextLevel) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
//flash something method here
flashTimer++;
}
});
timer.start();
}
and then check your flashTimer if it reaches the number you want then just stop the timer by timer.stop();
Just an idea which seems to me a bit simpler. the 1000 value is milliseconds which is passed and executes the code inside the actionPerformed method every 1 sec.
Hope it helped

Java Threads are not running on separate objects

I am working on a school project that involves generating two separate Swing Canvas objects which animate Breadth/Depth-First Search Algorithms on cloned copies of a Matrix/Grid Data Structure I have designed.
I have created a few classes that help translate the Matrix/Grid into graphics, which are combined in a SearchAnimation class that acts a ViewController for managing the animations. In the image below, they appear on the right (not in the yellow background area). Each SearchAnimation object includes a JLabel, Canvas, and White Background.
Below is a screenshot of the layout:
The JFrame contains two instances of the SearchAnimation Class in the Application Controller Class (ICL.java). These animations must run concurrently. I have created separate Threads for each animation, passing it separate SearchAnimation objects:
public void setupDepthFirstPanel() {
// Create a new GridGraphic Panel
//canvasDepthFirst = new GridPanel(null, DEPTH_FIRST_LABEL);
mDepthAnimation = new SearchAnimation(null, SearchAnimationType.DEPTH_FIRST_ANIMATION);
mDepthThread = new Thread(mDepthAnimation, "Depth Thread");
}
public void setupBreadthFirstPanel() {
// Create a new GridGraphic Panel
//canvasBreadthFirst = new GridPanel(null, BREADTH_FIRST_LABEL);
mBreadthAnimation = new SearchAnimation(null, SearchAnimationType.BREADTH_FIRST_ANIMATION);
mBreadthThread = new Thread(mBreadthAnimation, "Breadth Thread");
}
I start the Threads in the ActionListener class that responds to the Click Event of the button that labeled "Label Components":
if ( source == labelComponents ) {
if (DEBUG && DEBUG_CLICK_LISTENER) System.out.println("\"Label Components\" Button Clicked!");
/*This is where the call for the labelBreadth and labelDepth of the
ICLLogic class is going to occur*/
// Run Animation
// Set Up Threads
System.out.println("ICL.ActionPerformed - Current Thread: " + Thread.currentThread());
//mBreadthThread = new Thread(mBreadthAnimation, "Breadth Animation");
//mDepthThread = new Thread(mDepthAnimation, "Depth Animation");
// Start Threads
mBreadthThread.start();
mDepthThread.start();
}
When the program runs and the "Label Components" button is clicked, only one of the graphics starts animating, but it seems as though both SearchAnimation Threads are running within a single JPanel/Canvas since the animation does not follow the logic of either algorithm.
Here is the implementation of the Runnable Interface within SearchAnimation:
// THREAD METHODS
/** Implementation of the Runnable interface for Multithreading of the
* SearchAnimation Class, which allows multiple SearchAnimations to run Concurrently.
* In this case, the Breadth & Depth-First SearchAnimations
*
*/
public void run() {
System.out.println("Thread Started - " + mAnimationType.toString());
// Run the Animation
step();
}
Which eventually calls determineSearchType() that switches on an Enum to pick the appropriate Algorithm:
public void determineSearchType(Pixel p) {
// Animate a single pixel movement, step depends on AnimationType
if (DEBUG && DEBUG_STEP_NEXT_PIXEL) { System.out.println("Determining Animation Type..."); }
switch (mAnimationType) {
case BREADTH_FIRST_ANIMATION:
if (DEBUG && DEBUG_STEP_NEXT_PIXEL) { System.out.println("Animation Type: Breadth-First"); }
// Begin Breadth-First Search
stepBreadthSearch(p);
break;
case DEPTH_FIRST_ANIMATION:
if (DEBUG && DEBUG_STEP_NEXT_PIXEL) { System.out.println("Animation Type: Depth-First"); }
// Begin Depth-First Search
stepDepthSearch(p);
//simpleDepthSearch(mCurrentPixel);
break;
}
}
When I alternate commenting them out, each Thread/Animation executes in its own JPanel/Canvas graphic and produces the expected results. I am pretty new to threading and I'm sure someone has an easy solution. Any ideas at how I can fix the issue that the animations won't animate simultaneously?
option1 :
to give another Thread chance to be executed. at the end of thread code, try yield() and see if you have some luck
Thread.currentThread().yield();
option2 :
add flag in your thread, to pause and continue the thread. the idea is
after thread 1 finish the step
- pause thread 1 - then start thread 2 - after thread 2 finish the step
- pause thread 2 - and continue thread 1 again.

enforce a function to wait till mouse clicked

I have been stuck for the past month and I did not find any solution.
my problem is I am writing a game of four players. three are computers and one human.
so there are a play() function for computers and one Overridden play() function for human.
here is the function which human player will use
#Override
public void play(){
for(int i=0 ; i <13;i++){
getJLabels()[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int Index = getIndex(getJLabels(), (JLabel)evt.getSource());
getJLabels()[Index].setIcon(getHand()[Index].getBackSide());
getPlayerJLabel().setIcon(getHand()[Index].getCardImage());
setObjectForPlay(getHand()[Index]);
}
});
}
temp = getObjectForPlay();
return temp;
}
Other three players use play() and return an object automatically. i mean the mouselistener is only for this human.play() function
i am running these functions from nested loop. when a round of loop complete every player complete his play() turn and then next loop start. and so on.
Problem is computers play() functions are not waiting for human to click.
I want that when loop play the human Play() then wait for human to click and return object. when human play() end with click then next computer play() call
My english is poor thanks for understanding
waiting for nice solution

How to start a number of moving Sprite objects on different time?

I created a live wallpaper service using AndEngine library. On screen there are a number of bird Sprite objects that flying repeatedly from the left to right started in random y-coordinate (I'm using LoopEntityModifier and PathModifier for this, see my previous question if you're curious). The birds shouldn't start flying in same time, but there is a gap/interval about 3 seconds before another bird showed up from left most screen.
The question is what technique that I have to use to achieve that?
I had created array of Sprites to hold the bird sprites. The code is like this...
public class MyLiveWallpaperService extends BaseLiveWallpaperService {
private BirdSprite[] birdSprites; // BirdSprite is actually an extension class from AnimatedSprite
...
#Override
public Scene onLoadScene() {
...
birdSprites= new BirdSprite[4];
for (int i=0; i<4; ++i) {
birdSprites[i] = new BirdSprite(0, 0, birdTextureRegion);
scene.getChild(LAYER_FRONT).attachChild(birdSprites[i]);
}
}
}
The above code produces four birds that show-up on left screen in same time. I tried by adding Thread.sleep(3000) before calling attachChild, but it affects whole application. The live wallpapaper application become hanged for several seconds when started.
This is the solution I found by using TimerHandler:
scene.registerUpdateHandler(new TimerHandler(3, true, new ITimerCallback() {
#Override
public void onTimePassed(TimerHandler pTimerHandler) {
// your code here will be executed every 3 seconds (see 1st argument of TimerHandler)
...
scene.getChild(LAYER_FRONT).attachChild(birdSprites[i]);
}
}));
Please let me know if you have better solution.

Java Wait Function

I was wondering if you guys could help me out. I'm trying to make an animation program with Java's built in graphics module... The thing is, Java executes everything at once; there isn't any time between the different animations. The end product is just the last picture. I need a function that puts like half a second in between each of the pictures.
Any help is appreciated.
Specs: Blue-J, JDK 6.
Edit: Btw, I'm a Java Newbie, and this is a class thing. The assignment was to make an animation, and press 'c' to go forward each frame, but I think thats kinda ghetto, so I want something better.
Create a javax.swing.Timer that executes each X milliseconds, and draws one frame each time it is triggered.
This is the example from the javadoc:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
Modify the delay, to e.g. 20ms. That will give you about 50 frames per second if your painting doesn't take too long.
Maybe a simple sleep might be enough for you?
Thread.sleep(milliseconds);
Change your
public static void main(String[] args){ to
public static void main(String[] args) throws InterruptedException {
and inside that method type in
Thread.sleep(milliseconds you want);

Categories

Resources