I am building a game of top trumps and I need my program to pause execution until a JButton is clicked. I have done a google search and there does not seem to be any wait for mouse event option in Java. I have created an alternative solution but I suspect it is eating up memory. This is working for and returns what I need. Is this potentially eating up memory? is there a more efficient solution to this? (I added a method that pauses execution for 1 second and this does seem to slow the amount of memory being used)
Update: I am creating a game of trumps and when my card information is printed the game needs me to pick a skill. I.E There is 5 buttons to choose from that return a string value;
public String getPick() {
pick = getMouseClick();
System.out.println(pick);
return pick;
}
private String getMouseClick() {
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(String e) {
setPick(e);
}
});
return pick;
Related
private class Listener implements ActionListener, MouseListener {
#Override
public void mousePressed(MouseEvent eventClick) {
// Recovery Card from JLabel //
JLabel labelCardClicked = (JLabel)eventClick.getSource();
ImageIcon imageCardClicked = (ImageIcon)labelCardClicked.getIcon();
Card clickedCard = getCardWithFileaname(imageCardClicked.getDescription());
// FLIP //
imageCardClicked = new ImageIcon(clickedCard.getLogo());
imageCardClicked.setDescription(clickedCard.getId());
labelCardClicked.setIcon(imageCardClicked);
sameCardPressed(labelCardClicked, clickedCard);
if(numberCardsClicked == 2) {
Boolean status = controller.sameCard(cardsInGame);
//timer.start();
validateGameUser(status); // Problem here
//To be continued ...
}
My program is the typical card game that when you click on a card, it flips over, and if you make a match, they are removed from the GUI.
Well, when you start the game and click on one card, it flips, but when you click on the second one you don't see that effect. I think it's because there's a one second timeout missing before you get to validateGameUser (status);
That's the only reason I see for it to fail me..., the first card flips and we see it, but the second one doesn't .... when I debug with "System.put.println()" I can see that the card flips, but it's not seen in the GUI as in the first card, that's why I think it reaches validateGameUser (state) very fast and you don't notice the change (since they are removed from the GUI). So I was thinking about a timer .... but I don't know how to link it to my program :/
I'm coding a game and I'm trying to get the value of a dice roll from a button click in my UI.
I'm not too familiar with the MVC principles but I heard it's the way to go. Any tips on how to get there from this code ?
int move = -1;
while (move == -1) {
this.btnLancerLeD.addMouseListener(new MouseAdapter() {
public int diceRoll;
#Override
public void mouseClicked(MouseEvent arg0) {
diceRoll = jeu.getDe().lancer();
move = diceRoll;
}
});
}
I'm trying to get diceRoll value to move my players on the board.
First, you should only call addMouseListener() once rather than doing it repeatedly in a while loop. Second, you can do the logic of the "move" all inside mouseClicked(). You probably need an if statement.
Note that Swing already contains the logic to wait for the user to do something. This is the whole point of event listeners. They are only fired when that event occurs. In the case of a button, you should use an ActionListener instead of a MouseListener. For more details, I suggest that you check out the official Oracle tutorials for Swing. You can find these with a quick Google search.
I'm facing a problem since many days without finding an anwser.
In the code i will not put all my code because it will just complicate the question.
I have a game class which is rendering each frame.
public class MyGame implements ApplicationListener {
#Override
public void render() {
//handling event
handleEvent();
//update player position
updatePlayerPosition();
//rendering the player using a batch
renderPlayer();
}
public void handleEvent(){
//when the player prees on C i'm calling a method in another class
// when i do some processing
if (Gdx.input.isKeyPressed(Keys.C)) {
OtherClassForProcessing() ocp = new OtherClassForProcessing();
ocp.process();
}
}
//in this method i have to ask the user to choose an option
//i have to think to stop running this method until the
// user choose an option
//this method has to return a value
public static int displayChoice(List<Integer> ListOfInteger){
return 0;
}
}
public Class OtherClassForProcessing(){
public void process(){
int value= MyGame.displayChoice() ;
}
}
The question is how can i ask the user to choose an option in the displayChoice method.
What kind of widget will do this work.
I tried to use another screen for that , but the methode don't stop running .
How can i ask the program to stop until the user choose an option.
Thank you
what i tried is :
#Override
public static int displayChoice(List<Integer> ListOfInteger){
//i change the screen when i ask the user to choose from many options
setScreen(new PauseScreen());
a wile loop hwo run until the user choose an option from the other screen
while(PauseScreen.notYetChoosen){
Gdx.app.log("display message ", "the user not yet choose an ption");
}
return PauseScreenValue;
}
When i put the while loop:
the screen don't change from the game to the PauseScreen.
the loop run without stoping
the screen block
But when i remove the while loop the screen change to the PauseScreen but the method finish without waiting the user to choose an option.
EDIT
i tried to avoid using another screen unfortunantly even when i used a window the screen block
You can use a separate screen for this, I do not know your code structure exactly but here is how you can do it conceptually if you were trying to get input from a "pop up" or "pause screen" or something of that nature.
Inside of your Game Screen have a boolean which will be set when your "pop up" is displayed, for example isPaused, then you can use this boolean to skip over game logic while waiting for the screen to receive input.
For a more elegant approach you can use Game States which can represent which state your game is in. You can have a PLAYING state, GETTING_INPUT state, etc. Then you can run game logic depending on which state you are in.
EXAMPLE:
public void update (float deltaTime) {
if (deltaTime > 0.1f) deltaTime = 0.1f;
switch (state) {
case GAME_READY:
updateReady();
break;
case GAME_RUNNING:
updateRunning(deltaTime);
break;
case GAME_PAUSED:
updatePaused();
break;
case GAME_LEVEL_END:
updateLevelEnd();
break;
case GAME_OVER:
updateGameOver();
break;
}
}
EXAMPLE SOURCE AND MORE INFO:
LIBGDX SuperJumper Demo
https://github.com/libgdx/libgdx-demo-superjumper/blob/master/core/src/com/badlogicgames/superjumper/GameScreen.java
Response to your edit
The reason your code is not changing is because you have a while loop printing out to the Gdx Log until input is taken so your code is stuck in that while loop.
If you want to go this route, you can set a 'pause' variable inside your Game Screen to true and then set your screen to the pause screen. Inside of your Game Screens update logic, tell it not to update if paused.
public void update()
{
if(!paused)
{
//game logic
}
}
I don't know if the title actually makes my problem clear. I'm making a card game application. When the user and the computer both have played their cards off they should remain on the screen there for a certain until the computer plays the next card off.
I tried to solve this problem using thread.sleep() in try catch. And it's basically doing what it's supposed to do but it's not what I want it to do. The delay isn't between the computer playing one card and then the second one off. It is between the user pushing the button (for a card) and the appearance of this card on screen.
Here is the relevant code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel1.setIcon(//new Icon of the card);
jPanel1.remove(jButton1);
jLabel2.setIcon(//new Icon of the card);
if(//proving whether the computer played the highest amount off)
{
disableButtons();
sleep();//waiting for a certain time...
playCard();//...until playing the next card off
}
}
public void sleep()
{
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
}
}
Welcome to StackOverflow. If you sleep in the UI thread, the UI will not reflect all your drawing commands until you enter the main loop again. Look into swing timers.
This is a follow up to a previous question I had. I have a Battleships game with two boards. When the user clicks on the computer board an action occurs, along these lines:
public void mouseClicked(MouseEvent e)
// Get coordinates of mouse click
if (//Set contains cell) {
/add Cell to set of attacked cells
//Determine if set contains attacked cell.
// If yes, hit, if no, miss.
checkForWinner();
The checkForWinner method determines if the game has been won yet. If it hasn't it calls a nextTurn method which changes the current turn. If the currentTurn is set to Computer, a ComputerMove() method is automatically called.
When that method finishes, it again checksforWinner, changes turn and waits for the user to click on the grid to start the cycle again.
Ideally, I'd like to have sound effects, or at the very least a pause between moves. However, no matter how I use Thread.sleep, or TimerTask, or anything else, I can't get it to function correctly.
If I use a simple Thread.sleep(500) in the CheckforWinner method, or in the ComputerMove method, all that happens is the human's go is delayed for the set amount of time. As soon as his move is executed the computer's move is completed immediately.
I know very little about threads but I assume this is because all the initiation of the bouncing back and forth between methods begins with a method in the mouse listener.
Given the set up of my system, is there a way to implement a delay without radically changing things?
Edit: May as well include the classes:
public void checkForWinner() {
if (human.isDefeated())
JOptionPane.showMessageDialog(null, computer.getName() + " wins!");
else if (computer.isDefeated())
JOptionPane.showMessageDialog(null, human.getName() + " wins!");
else
nextTurn();
}
public void nextTurn() {
if (currentTurn == computer) {
currentTurn = human;
} else {
currentTurn = computer;
computerMove();
}
}
public void computerMove() {
if (UI.currentDifficulty == battleships.UI.difficulty.EASY)
computerEasyMove();
else
computerHardMove();
}
public void computerEasyMove() {
// Bunch of code to pick a square and determine if its a hit or not.
checkForWinner();
}
Ideally, I'd like to have sound effects, or at the very least a pause between moves. However, no matter how I use Thread.sleep, or TimerTask, or anything else, I can't get it to function correctly.
You should be using a Swing Timer. Something like:
Timer timer = new Timer(1000, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
currentTurn = computer;
computerMove();
}
});
timer.setRepeats(false);
timer.start();