is there a better way to swap players symbols? - java

I'm making XO game by JavaFX, so I need a way to swap between "X"s and "O"s with each new turn, could you please check what I've come up with and tell if there a better way to swap them
boolean turnSwaper=true;
public void play(ActionEvent e){
String player="";
if(turnSwaper){
player="X";
turnSwaper=false;
}else {
player="O";
turnSwaper=true;
}
Button pressed=(Button)e.getSource();
pressed.setText(player);
pressed.setDisable(true);
}

Related

Can I get data from a Swing Mouse Adapter/Listener method?

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.

Wait for Mouse Event

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;

How do I update the current keyPressed in a KeyEvent for java?

I would be extremely grateful if some one could help me with my code, I'm learning code as I develop games.
I'm trying to make the controls on a basic PONG game feel smooth, but I have this problem with the keyEvent/keyPressed. I am using A to go left, D to go right, when I hold D then press A, without letting go of D it will notice the change and go left, but once i let go of A with D still held down, the keyEvent will not notice that D is held down, which makes the racquet not move until you press D again.
Is there a way to tell the keyEvent or keyPressed to update on whats happening at the moment and react to it?
Here's the fragment of the code...
p.s. I'm new to stack overflow and not a fluent java programmer I'm still learning. I'm sorry if my question is very vague or unspecific...
also, move(1) makes coordinates of the racquet move x+=1 and move(-1) x-=1*/
Fix attempt#1 :
I tried using a return statement after a change was made hoping that would work, no result...
public void keyPressed(KeyEvent e) {
//MOVE LEFT
if (e.getKeyCode() == KeyEvent.VK_A){
if(e.getKeyCode() == KeyEvent.VK_D){
move(1);
//maybe update?
return;
}
else
move(-1);
}
//MOVE RIGHT
if (e.getKeyCode() == KeyEvent.VK_D){
if(e.getKeyCode() == KeyEvent.VK_A) {
move(-1);
//maybe update?
return;
}
else
move(1);
}
}
The best way to handle this situation is to create a boolean array and store the values of everything in there and then use it later. This allows for updates to be handled a bit more smoothly and allows for you to have a bit more of organization. To create the array at the top type
public static boolean[] keys = new boolean[999];
Then in the press method do
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
And finally in the release method
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
Then to reference it later simply use
[class].keys[KeyEvent.[key]]

Properly implementing a delay in a game

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();

Problems with TicTacToe game in java? using getText().equals() with jButtons

Not to sure about why this code is not working as intended and hoping you could help me figure it out. I am working on a tictactoe game from a series of tutorials that use jbuttons. What i have is a method in my main class that "checksforwin" each time a button is clicked. Using print statements i found that my method does run each time a button is clicked however the getText().equals("_") conditions do not operate properly.
This code is part of my tictactoe.java and all works properly. this event is copied 9 times for each button.
public void button1ActionPerformed(ActionEvent e) {
if(button1.getText().equals("")){
if(Main.playerTurn==true){
button1.setText("X");
Main.checkforwin();
Main.playerTurn = false;
}else{
button1.setText("O");
Main.checkforwin();
Main.playerTurn = true;
}
}
}
This code is part of my main.java which houses the checkforwin method. The check for win chunk of code is repeated multiple times for each possible win in tictactoe for both the player 1 and computer(player2).
public class Main {
public static boolean playerTurn = true;
public static boolean playerWon = false;
public static boolean computerWon = false;
public static tictactoe board = new tictactoe();
public static void checkforwin(){
System.out.println("testing1");
//horizontal row 1
if(board.button1.getText().equals("X")){
System.out.println("testing2");
if(board.button2.getText().equals("X")){
if(board.button3.getText().equals("X")){
playerWon = true;
computerWon = false;
System.out.println("Player 1 won");
}
}
}
}
The method will output testing1 every time a button is clicked, however it will never print inside the conditions.
Any help or advice would be greatly appreciated thanks!
My guess is its not picking up the button text change - after the button text change (button1.setText("X");) etc - you need to add it to the panel again, so panel.add(button1); or whatever they're stored on
I was taking a quick look at your coding and not entirely sure, but "maybe" you should try using AND operator in your conditional IF statement? For example:
if(board.button1.getText().equals("X") && board.button2.getText().equals("X") && board.button3.getText().equals("X")){
playerWon = true;
computerWon = false;
System.out.println("Player 1 won");
}
You could use these types of conditional statements to say either player/computer has won, providing the horizontal or vertical buttons equal X or O.
There is probably a more efficient way though to do it though, but this is the first thought that occurred to me so you could try it out!
I hope it helps!

Categories