enforce a function to wait till mouse clicked - java

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

Related

Java/Processing mousePressed in loop not working

So I was making a simple game in Java + Processing where there were buttons and loops in draw(). Apparently the PApplet function mousePressed() doesn't work constantly if there is a loop, so I tried putting my own checkmouse() function to be checked during the loop. However, it still doesn't work. How do I make it so that I can run a game with while-loops and constantly check for mousePressed at the same time?
//draw() func
public void draw() {
for (int i = 0; i < 10000; i++) { //to simulate a while loop
//do something, like run some other functions that create the buttons
checkmouse();
}
}
//checkmouse function
public void checkmouse() {
if (mousePressed) {
System.out.println("x");
}
}
When I click the mouse in the processing window, it never shows "x" even though checkmouse() runs every time it loops, so theoretically it should be checking it pretty constantly while the loop runs.
Also could someone explain why this doesn't work?
boolean esc = false;
while (!esc) {
if (mousePressed) {
System.out.println("x");
esc = true;
}
}
The event variables (mousePressed, keyPressed, etc.) are updated between calls to the draw() function.
In other words: the mousePressed function will never change within a call to the draw() function. You need to let the draw() function complete and then be called again if you want the event variables to be updated.
Behind the scenes, this is because Processing is single-threaded. (This is by design, because multi-threaded UI programs are a nightmare.)
Taking a step back, you probably don't want to include a long loop inside your draw() function. Take advantage of the 60 FPS loop that's implemented by Processing instead.

how to call methods in java simultaneously?

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.

Updating JLabel Icon with something, waiting 2 seconds, then updating with something else?

here is the relevant portion of my code:
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == push) {
g.getHuman().beAPig(true);
}
else {
g.getHuman().beAPig(false);
}
// take p1 turn and check if players switched
if (!g.gameOver() && g.playGame()) {
while(!g.playGame()); // loop until players switched
}
updateLabels();
if (g.gameOver()) {
gameOverDialog();
}
}
}
//-----------------------------------------------------------------
// Updates the score labels and die images.
//-----------------------------------------------------------------
private void updateLabels() {
die1Image.setIcon(pair.getDie1Image());
die2Image.setIcon(pair.getDie2Image());
p1RoundPointsLabel.setText(Integer.toString(g.getHuman().getRoundPoints()));
p1GamePointsLabel.setText(Integer.toString(g.getHuman().getGamePoints()));
p2RoundPointsLabel.setText(Integer.toString(g.getComputer().getRoundPoints()));
p2GamePointsLabel.setText(Integer.toString(g.getComputer().getGamePoints()));
sumLabel.setText(pair.toString());
}
So the game is called PigDice. A player and computer take turns rolling a pair dice, etc. When a one on either die is rolled, that player's turn is over, and it passes to the other player. The problem is when I roll a one, it instantly switches to the computer, which instantly takes its turn, instantly switching back to me and updating the dice images with the computer's last roll. What I am trying to do is whenever the human rolls something with a 1 in it, it updates the die images so you can see what they rolled, then pauses for 1-2 seconds, THEN updates all the labels with the results of the computer's turn.
I've read a little bit about the EDT (don't have a very complete understanding), and I've tried using Thread.sleep() and InvokeLater() unsuccessfully.
Thanks.

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

Relaunch a java console application code

I'm searching on the internet for hours and i cannot find the right answer that works for me.
So.. I made a game called 'seabattle'
After playing that game the console comes with the question to play again.
System.out.println("Well done! " + whosturn.getName() + ". A ship down!" );
System.out.println("Hurraaaaaayyyyy, All boats down!!");
System.out.println("Do you want to play this game again? (y/n) ");
input = scanner.next().toLowerCase();
if(input == "y"){
System.out.println("The game should start again now..");
System.out.println("Butttttttt, I don't know how to...");
}
else{
System.out.println("Thank you for player Battleships!");
System.out.println("See you next time ;)");
}
}
else{
FiredPosition.setDisplayValue('*');
System.out.println("Good job, you hit a ship!");
switchTurn();
}
If the user types y in console. The game should start again.
I read something about Main(args) or something like that.. That didn't work for me because this is another class.
I hope you guys can help me?
Ciaoo
If your main class SeaBattle is currently as this:
public class SeaBattle {
public static void main(String[] args) {
...
}
}
you could change it the following way:
public class SeaBattle {
private static String[] args;
public static void run() {
//do the same than main() previously
}
public static void main(String[] args) {
SeaBattle.args = args;
run();
}
}
Then to relaunch the game,
SeaBattle.run();
A simple answer is: Whatever you do to start the game in the first place, do it again when you detect the 'y'.
However, a more in depth answer involves the use of an object to store and update the game state, it is not fully clear from your description whether you are currently doing this. So if it is a battleships type game the object may contain a 2d array for the game area, and perhaps a variable to store whose turn it is. This object would have an 'initialise' method where you randomly select where the ships are in the game area, set the value for whose turn it is, etc.
Your main method would interact with this object, so it would call the game object's initialise method, and after each turn it would call another method (e.g. 'isGameFinished') to check whether the game is over. The isGameFinished method would check if all of the ships have been destroyed and return true if so. If it returns true, then the user would be prompted for a new game. If they enter 'y', then you can either create a completely new object of the game state or just call the game state's initialise method again. You will then have a new game state to begin a new game with.

Categories

Resources