Multiple classes with Mouse.next() - java

As the title already shows I have an issue with the function "Mouse.next()".
I'm programming my own buttons at the moment and for that I have to check, if the left mouse-button was pressed. I thought, that I can do it so:
while(Mouse.next()) {
if(Mouse.getEventButtonState() && Mouse.getEventButton() == 0) {
// some code..
}
}
This also works, if I only have one instance of my button. But if I add another instance the while loop never gets called for the second (last created) button...
Does somebody have any idea, why this could happen?...
And also what do these functions (found them on the internet) Mouse.getEventButtonState(), Mouse.getEventButton() == 0 and Mouse.isButtonDown(0)
Mouse is from org.lwjgl.input.Mouse
With another instance I mean something like: MyButton button = new MyButton();
EDIT:
My Question is: How can I get Mouse.next() to work with multiple instances of the surrounding class...

Because Mouse is a Singleton . As long as it is Singleton calling next will consume the Event. You can not consume the same event two times! When first object calls next() it consumes it and when the second calls next() the is no second click to consume.

The issue is that getEventButton() returns a different number depending on which button was pressed. What you should do instead is something like:
while (Mouse.next()) {
if (Mouse.getEventButtonState()) {
int buttonId = Mouse.getEventButton();
switch (buttonId) {
case -1: break; // no button was clicked
case 0:
// code for first button
break;
case 1:
// code for second button
break;
}
}
}

Related

How do I switch between two views being visible?

I am making an application that helps score a table tennis game. I am at the final stages but I am having trouble with switching the server around every two points. I have given it a lot of thought but I can only get it to switch once. I know it is probably an easy solution but it's just not coming to me.
Here's how I am switching it once. I am using a count each time the button is pressed and when it reaches a number divisible by 2 it switches to the right.. However, using this logic is making it difficult to switch back! Thanks in advance.
public void serveSwitch() {
TextView leftServe = findViewById(R.id.leftServe);
TextView rightServe = findViewById(R.id.rightServe);
serverCount++;
if (server.serve=="left") {
if (serverCount % 2 == 0) {
rightServe.setVisibility(View.VISIBLE);
leftServe.setVisibility(View.GONE);
}
}
The part I'm struggling with is the logic on how to switch visibility every two points
If I get your point right, you want to toggle the visibility from off to on every two points and vice versa
You can do something like:
...
if (server.serve=="left") {
if (serverCount % 2 == 0) {
switch (rightServe.getVisibility()) {
case View.GONE:
rightServe.setVisibility(View.VISIBLE);
break;
case View.VISIBLE:
rightServe.setVisibility(View.GONE);
break;
}
switch (leftServe.getVisibility()) {
case View.GONE:
leftServe.setVisibility(View.VISIBLE);
break;
case View.VISIBLE:
leftServe.setVisibility(View.GONE);
break;
}
}
}
Note: I left the equality as-is as you say there is no problem with it. but in general you should use .equals() when it comes to compare strings in java.

Method is called more than once from one ActionEvent

I'm trying to code a trivia based game with ActionEvent based buttons. I organized each specific event that is connected to JButton instances in a if-else structure and inside each of these structures, a method would be called. One of these methods would increment a variable that holds the number of the answers that are correct (cor) and wrong (inc):
public void compare(String sel , String ans)
{
//if correct
if(sel.compareToIgnoreCase(ans) == 0)
{
q.setText("Correct! 10 points added!");
score += 10;
cor++;
}
//if incorrect
else
{
q.setText("Incorrect! The correct answer was: " + ans);
inc++;
}
}
This set of code would be run from this:
public void actionPerformed(ActionEvent event)
{
if(e.equals("GUESS"))
{
userGuess = entry.getText();
answer = ans.get(currentQuestionIndex);
base.remove(entry);
base.remove(submit);
submit.setText("OK");
submit.setActionCommand("OK");
submit.addActionListener(this);
base.add(submit);
compare(userGuess, answer);
}
...
}
However, whenever the compare method is called, the inc and cor value seems to increment by an ambiguous value. For example, if I were to answer one question right, the new value for cor would be 2 instead of 1. When I answer another right, cor would be 5 instead of two. I tried using tracers in my code but so far, I appears that the program detects the actionEvent that runs compare() is being pressed multiple times, and as a result, it runs said code multiple times. How can I fix my code so that these variables can be incremented correctly by 1.
submit.addActionListener(this);
Don't add the ActionListener in the actionPerformed() method.
Each time the actionPerformed is invoked you add another listener, so when you click on the "Submit" button you have code that is executed multiple times.

Switch-case uses same case repeatedly after first choice, how do I reset or flush it before use to work correctly?

Switch-case runs properly the first time but continues using the same initial choice over and over again. I need it to reset before this block of code runs so it chooses a different (or same) case when needed.
This is for a school project where a fox chases a rabbit. I must code the rabbit. I have the switch-case developed so as to use it's proximity to a bush as the argument that is switched on. This determines what the rabbit will do. It works properly the first time but continues with the same case after it moves and the previous case runs again on the rabbits next turn. After some research I found that I should wrap it up in a do-while statment with some flags to exit the loop and I did but the same problem continues.
if (noMansLand == false) {
needDirection = true;
do{
switch (directionToBush) {
//N-------------------------------------------------------
case 0:
if (look(7) == Model.BUSH) {
if (distance(7) == 1) {
currentDirection = 6;
if (look(6) == Model.BUSH) {
if (distance(6) == 1) {
currentDirection = 5;
}
}
}
} else {
//WANTED DIRECTION
currentDirection = 7;
}
//FOX ESCAPE PLAN
//code...
needDirection = false;
return currentDirection;
//E-------------------------------------------------------
case 2:
//similar code...
//S--------------------------------------------------------
case 4:
//similar code...
//W--------------------------------------------------------
case 6:
//similar code...
}while(needDirection == true);
}
There is ALOT more code and will happily show whole thing for help. The game works on an grid interface where the fox and rabbit take turns "looking" and moving by one grid in 1 of 6 directions (I only show 4 cardinal in my snip of the switch code). I have my rabbit look for the nearest bush to get fox to chase it around until max turns elapses. The rabbit gets to closest bush fine and upon reaching 1 distance from bush turns "noMansLand" to false and initiates switch-case block. The first turn of this works exactly as written and rabbit moves in correct direction but on the rabbits next turn it continues with the same case as if the bush is in the same direction it was last turn before moving. I'm assuming it is storing the old direction with the switch case but I do not know how to reset or flush this data.
switch (directionToBush) {
directionToBush is 0?
where is it changed? Not in your snippet!
If it is not changed it stays 0 in all loop iterations.
It would help if you can show where the switch case variable 'directionToBush' is being initialized and how it is being changed in the switch case. As long as you keep changing this variable basing on the cases, you should be fine. There no need to reset anything. Good luck!

Android Studio if statement with OR (||) Function

I am creating a mobile application that updates users with the current score and final score in a football match. I want the textview displaying the score to show only the current or final score.
I am having trouble with the if statement. I need one of the fields to contains something in order for a record to be created so I have:
if (!(et_currentgoals.getText().toString().isEmpty()) || !(et_finalgoals.getText().toString().isEmpty()){
}
Inside this if statement I was another that updates the textview with the correct values. So if the final number of goals was entered, the current goals are discarded. Would the best way be something like this:
if(!(et_finalgoals.getText().toString.isEmpty()){
tv_goals.setText(et_finalgoals.getText().toString();
}else{
tv_goals.setText(et_currentgoals.getText().toString();
}
Does this cover both scenarios or am I missing something?
Having that second if block inside the first will work, but there's a simpler way.
This single if will work.
if (!et_finalgoals.getText().toString.isEmpty()) {
tv_goals.setText(et_finalgoals.getText().toString();
} else if (!et_currentgoals.getText().toString.isEmpty()) {
tv_goals.setText(et_currentgoals.getText().toString();
}
In other words, these two blocks are equivalent
if (a || b) {
if (a) {
// a
} else {
// b
}
}
if (a) {
// a
} else if (b) {
// b
}
If I'm understanding correctly, you are executing additional code inside of that first if statement, after setting the tv_goals text. To do that now, you can just check the text of tv_goals.
if (!tv_goals.getText().toString.isEmpty()) {
// Do additional code
}
If this is the case, it ends up being the same amount of code as your original solution. You should just pick whichever way is more clear to you.

TicTacToe win conditions problems

New programmer here, writing a Tictactoe game using Java on Eclipse.
I have problems with my win conditions I think. It comes up with the error:
Exception in thread "main" java.lang.NullPointerException
at Game.NoughtsCrosses.(NoughtsCrosses.java:106)
at Game.Main.main(Main.java:5)
Here is my win conditions bit. It's not well made imo, but I'm having problems when compiling. Can anyone spot why? Ty!!
I have squares set up in a 3x3 grid, 0 -> 8. Each button has its own text which is set to X or O when clicked by each player.
winconditions code:
if (square[0].getText().equals(square[1].getText()) && square[1].getText().equals(square[2].getText()) != square[0].getText().isEmpty()) {
win = true;
}
Full Pastebin of code
Thanks again :) Any questions, I can elaborate :D
It looks like one of the squares text is null. One thing that is important to remember is that an empty string is not the same thing as null. In java, if you haven't specifically assigned a value to a String then it will be null. To fix this, you will want to explicitly set each squares text to "" (an empty string) when you set up your game board.
Well I took the code that you provided and after significant finagling was able to make a fully functioning Tic-Tac-Toe game. You were mostly on the right track with what you were doing you just needed to first begin with a design.
In my NoughtsCrosses class I have the following:
class Action implements ActionListener
This has a JButton attribute that I pass in through a constructor
In the actionPerformed
set the text
disable the button
increment the counter
check if someone wins
If there is a winner or draw game ends set the "Play again?" text
else call the changeTurn function
class Reset implements ActionListenter
This has a JButton attribute that I pass in through a constructor
In the actionPerformed
I call the resetGame function
function changeTurn
function resetGame
function checkForWinners
as a hint, this is my implementation of the Action class and an example of the constructor I mentioned
class Action implements ActionListener{
private JButton button;
public Action(JButton button){
this.button = button;
}
public void actionPerformed(ActionEvent e) {
button.setText(letter);
button.setEnabled(false);
counter++;
boolean gameOver = checkForWinners();
if(!gameOver)
changeTurn();
else{
newgame.setText("Play again?");
newgame.addActionListener(resetButton);
}
}
}
a call like new Action(square[i]) is what you need to make this work.
Note: the resetButton is of the Reset class I mention above much like the Action class it has the same construct that I passed newgame into.
It seems like your win-condition check is not within your actionPerformed code, but on the class level, hence it is possibly called before the window is populated with your buttons.
Try placing the check inside the actionPerformed like this: http://pastebin.com/xRViSUzy
What is the scope (most simply, which curly braces) is the problematic line inside of?
It was a bit tricky to tell based on your indentation, but it appears to me that your "if" was not inside a method (e.g. the constructor). I would guess that you intended this line and the ones around them to be executed after the lines in the body of your constructor where the squares are initialized. Instead, these lines are being run beforehand and therefore the call to "new" haven't been run yet.
I think that if you do some restructuring to move these conditions into your constructor or into another method that you call after construction then things will look a lot better.
Hope that helps.
If you're going to implement this type of solution, then simplify the job for yourself. Based on the tiny snippet of code I see above, it looks like you're really over-complicating the job you have to do.
char cell0 = //get that char, be it X or O
char cell1 = //
...
char cell8 = //
Now you can compare cells one by one to determine a victory. Your board game is set up as follows:
0 1 2
3 4 5
6 7 8
So you can just go in order:
Horizontal Solutions:
(cell0 == cell1 && cell0 == cell2)
(cell3 == cell4 && cell3 == cell5)
(cell6 == cell7 && cell6 == cell8)
Vertical Solutions
(cell0 == cell3 && cell0 == cell6)
//And so on
Cross Solutions:
(cell0 == cell4 && cell0 == cell8)
(cell2 == cell4 && cell2 == cell6)
This will check for your victory conditon.
The problem is that you have a surplus of braces in your code so that the statements in the question actually appear in an instance initializer block of the class NoughtsCrosses but none of the JButton components have been initialized yet as instance initializers are invoked before constructors which is where the JButton instantiated exist (but never called). When you attempt to invoke getText on the first element of the array square, a
NullPointerException is thrown.
To fix remove the additional braces to that the code is enclosed in the preceding ActionListener
class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
// existing code here
/// } remove
//} remove
// { remove
// win conditions. if true, set win==true; else set win
// here is where the compilation error is, next line
if (square[0].getText() == square[1].getText() ...) {
win = true;
} //etc
} <-- add this

Categories