Problems in moving the cursor with Google Lanterna Terminal - java

I am working with googlecode lanterna libraries. One of it's methods is "moveCursor(int x, int y)". I have a terminal field, and I want to move a character in it. But I'm having two problems:
The cursor does not go in the proper way it should. When I press Left Arrow after I have been pressing Right Arrow, it goes some steps down, than goes the right way. That happens for all arrows.
And the second question. Can anyone help me to move a character in the terminal field? Should I build any class or any method? Or I should modify this?
Thank you!
public void movePlayer()
{
int xLocation = s.getXLocation();
int yLocation = s.getYLocation();
while (true)
{
Key key = t.readInput();
if (key!=null)
{
if (key.getKind() == Key.Kind.ArrowLeft)
{
t.moveCursor(xLocation-1, yLocation);
xLocation--;
}
else if (key.getKind() == Key.Kind.ArrowRight)
{
t.moveCursor(xLocation+1, yLocation);
xLocation++;
}
else if (key.getKind() == Key.Kind.ArrowUp)
{
t.moveCursor(xLocation, yLocation+1);
yLocation--;
}
else if (key.getKind() == Key.Kind.ArrowDown)
{
t.moveCursor(xLocation, yLocation-1);
yLocation++;
}
}
}
}

If you do it like this the cursor moves properly and without any complications.
public static void movePlayer() {
int xLocation = s.getXLocation();
int yLocation = s.getYLocation();
while (true) {
Key key = t.readInput();
if (key != null) {
if (key.getKind() == Key.Kind.ArrowLeft) {
t.moveCursor(xLocation - 1, yLocation);
xLocation--;
} else if (key.getKind() == Key.Kind.ArrowRight) {
t.moveCursor(xLocation + 1, yLocation);
xLocation++;
} else if (key.getKind() == Key.Kind.ArrowUp) {
t.moveCursor(xLocation, yLocation - 1);
yLocation--;
} else if (key.getKind() == Key.Kind.ArrowDown) {
t.moveCursor(xLocation, yLocation + 1);
yLocation++;
}
}
}
}
I hope I could help you with your Problem.
To your second question I can't give an answer so far.

Related

my buttons for java gui don't seem to work, can someone help :(

Ive been trying to make buttons from checking if a factor is prime or not, the image below should be the output but im stuck trying to make the check button work.
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num = 10, i = 2;
if(e.getSource() == btnCheck) {
num=Integer.parseInt(userInput.getText().trim());
boolean flag = false;
while (i <= num / 2) {
if (num % i == 0) {
flag = true;
break;
}
++i;
}
if (!flag)
{subCenPanel.add(isPrime);}
else
{subCenPanel.add(notPrime);}
}
}
});
}
}
\\HERES THE PROJECT I NEED TO DO

Function Repeating Itself Even After Returning

I am making a Tic-Tac-Toe game with a computer player. However, whenever I call the computer's makeMove method, the computer continues to play without the user being able to do anything. Just to be sure that the function stopped, I made it return after each move, but it still plays the entire game without the user's input.
Here are the relevant parts:
Board Class:
public String addToBoard(char c, int square) {
if (!spaceFull(board, square)) {
int[] coords = getRowAndColumn(square);
//System.out.println("[" + coords[0] + "][" + coords[1] + "]");
board[coords[0]][coords[1]] = c;
return "VALID";
} else {
System.out.println("Space Is Occupied");
return "OCCUPIED";
}
}
public boolean spaceFull(char[][] b, int square) {
return (twoDimenToOneDimen(b).get(square - 1) == 'X' || twoDimenToOneDimen(b).get(square - 1) == 'O');
}
Computer Class
public void makeMove() {
int square;
//Checks For Any Winning Computer Moves
System.out.println("Here");
if ((square = nextMoveWinCheck(playerChar)) != 0) {
board.addToBoard(playerChar, square);
return;
//Checks For Any Opponent Winning Moves
} else if ((square = nextMoveWinCheck(opponentChar)) != 0) {
board.addToBoard(playerChar, square);
return;
} else {
//Checks If Computer Has First Move
if (boardEmpty()) {
board.addToBoard(playerChar, 9);
return;
} else {
//Moves Into Opposite Corner if Bottom Corner is Occupied By Itself
if (!board.spaceFull(board.board,1) && board.board[2][2] == playerChar) {
board.addToBoard(playerChar, 1);
return;
//Move Into Center If Second Move or Possible
} else if (!board.spaceFull(board.board,5)) {
board.addToBoard(playerChar, 5);
return;
} else if ((square = emptyCorner()) != 0) {
board.addToBoard(playerChar, square);
return;
} else {
board.addToBoard(playerChar, randomEmptySpot());
return;
}
}
}
}
If you want the full code, it's:
Computer
Board
Player
Tic-Tac-Toe Main Class
Your problem lies in your class Computer. On line 57, you assign board.board to tempBoard. However tempBoard still holds the reference to the object board.board, so whatever modifications you make there is reflected on the actual board. To resolve this, COPY the board values to tempboard:
http://www.java2s.com/Code/Java/Collections-Data-Structure/clonetwodimensionalarray.htm

JTextField. Find and highlight the word in a JTextArea

I wrote a code to find and highlight a word in a JTextArea and I'm hitting an issue and I'm too tired and with an headache to see my mistake.
I have a search bar(TextField) where I can enter a word and the word gets highlighter in my TextArea. Problem is, after I press my "ENTER" key, the TextField gets deselected and I have to click it again to find the next word. What am I missing?
findfieldpage1 = new JTextField();
findfieldpage1.setBounds(37, 295, 63, 24);
gtapage1.add(findfieldpage1);
findfieldpage1.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int code = evt.getKeyCode();
if(code == KeyEvent.VK_ENTER){
String find = findfieldpage1.getText().toLowerCase();
textpage1.requestFocusInWindow();
if (find != null && find.length() > 0) {
Document document = textpage1.getDocument();
int findLength = find.length();
try {
boolean found = false;
if (pos + findLength > document.getLength()) {
pos = 0;
}
while (pos + findLength <= document.getLength()) {
String match = document.getText(pos, findLength).toLowerCase();
if (match.equals(find)) {
found = true;
break;
}
pos++;
}
if (found) {
Rectangle viewRect = textpage1.modelToView(pos);
textpage1.scrollRectToVisible(viewRect);
textpage1.setCaretPosition(pos + findLength);
textpage1.moveCaretPosition(pos);
pos += findLength;
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
}
});
Youre not transfering the focus back to the text field after the search is done
Add at the end: Jtextfield.requestfocus()
Line 10 in your method is textpage1.requestFocusInWindow();, that's why it loses focus, because you're transferring it to the JTextArea.
In the end, to avoid the hassle. I added a JButton and changed the keyPressed to an actionPerformed. So everytime I click that button, it finds and highlights me the string I enter in the TextField. Thank you for your help guys, I appreciate it.
Add one more listener to textarea. After the focus is shifted to text area, this way it'll remain in textarea and the event (enter key press) etc will make the search happen.
/search filed begins/
JTextField findtext = new JTextField();
//findtext.setBounds(112,549, 63, 24);
frame.add(findtext,BorderLayout.BEFORE_FIRST_LINE);
findtext.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int code = evt.getKeyCode();
if(code == KeyEvent.VK_ENTER){
String find = findtext.getText().toLowerCase();
tarea.requestFocusInWindow();
//findtext.requestFocus();
//findtext.requestFocusInWindow();
if (find != null && find.length()> 0) {
Document document = tarea.getDocument();
int findLength = find.length();
try {
//int pos=0;
boolean found = false;
if (pos + findLength > document.getLength()) {
pos = 0;
}
while (pos + findLength <= document.getLength()) {
String match = document.getText(pos, findLength).toLowerCase();
if (match.equals(find)) {
found = true;
break;
}
pos++;
}
if (found) {
Rectangle viewRect = tarea.modelToView(pos);
tarea.scrollRectToVisible(viewRect);
tarea.setCaretPosition(pos + findLength);
tarea.moveCaretPosition(pos);
pos += findLength;
//Thread.sleep(2000);
// findtext.requestFocusInWindow();
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}//findtext.requestFocusInWindow();
}
});
/*control back to textarea*/
tarea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int code = evt.getKeyCode();
if(code == KeyEvent.VK_ENTER){
String find = findtext.getText().toLowerCase();
tarea.requestFocusInWindow();
//findtext.requestFocus();
//findtext.requestFocusInWindow();
if (find != null && find.length()> 0) {
Document document = tarea.getDocument();
int findLength = find.length();
try {
//int pos=0;
boolean found = false;
if (pos + findLength > document.getLength()) {
pos = 0;
}
while (pos + findLength <= document.getLength()) {
String match = document.getText(pos, findLength).toLowerCase();
if (match.equals(find)) {
found = true;
break;
}
pos++;
}
if (found) {
Rectangle viewRect = tarea.modelToView(pos);
tarea.scrollRectToVisible(viewRect);
tarea.setCaretPosition(pos + findLength);
tarea.moveCaretPosition(pos);
pos += findLength;
//Thread.sleep(2000);
// findtext.requestFocusInWindow();
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}//findtext.requestFocusInWindow();
}
});
/*search filed ends*/

How to output binary search method?

This is just your average binary search, in my program I use this search method to allow the user to look for book titles.
String [] binaryArray = {"4", "6", "10"}; //the chosen binary numbers to look for
public static Boolean binarySearch(String [] A, int left, int right, String V) {
int middle;
Boolean found = false;
while (found == false && left <= right) {
//If middle item == 0, returns true
middle = (left + right)/2;
int compare = A[middle].compareTo(V);
if (compare == 0) {
found = true;
} else {
if (compare >0) {
right = middle -1;
} else {
left = middle + 1;
}
}
}
if (left > right) {
return false;
} else {
return true;
}
}
Now I choose IF statements to output the correct response, but imagine if the database was for a real library with possibly millions of entries. This obviously would not work very well. So what is way a way I can find the response needed without IF statements? Any ideas or advice would be appreciated!
private void findBookActionPerformed(java.awt.event.ActionEvent evt) { //finds book...
String input = enterNumberField.getText(); //input number to see if it matches up
if ("4".equals(input)) {
binarySearchField.setText("Book Title" + binarySearch(binaryArray, 0, binaryArray.length-1, "4"));
} else if("6".equals(input)){
binarySearchField.setText("Book Title" + binarySearch(binaryArray, 0, binaryArray.length-1, "6"));
} else if("10".equals(input)){
binarySearchField.setText("Book Title" + binarySearch(binaryArray, 0, binaryArray.length-1, "10"));
}
}

Java : Keystate operation issue

I'm having a problem getting the screen to change to the image I want to display.
The image is a spritesheet which is set up as an array ( ie first screen is in array index 0 etc...)
I can change when I press the UP key and LEFT key and ENTER key, but the program will not display the correct image pressing the DOWN key.
I eventually want to discard the arrow key presses and subsituite them for numbers (the phone number keys ) 4 to return, 1,2,3 to go to certain pages and enter to go to the next page, if there is more information on a particular page.
private void actOnKeyStates(int k) {
if ((k & DOWN) != 0) {
Title = false;
HowToPlay = true;
Controls = false;
About = false;
}
if ((k & UP) != 0) {
Title = false;
HowToPlay = false;
Controls = true;
About = false;
}
if ((k & LEFT) != 0) {
Title = true;
HowToPlay = false;
Controls = false;
About = false;
}
if ((k & FIRE_PRESSED) != 0) {
Title = false;
HowToPlay = false;
Controls = false;
About = true;
}
update();
}
public void update() {
if (Title) {
Screen.setFrame(0);
}
if (HowToPlay) {
Screen.setFrame(1);
}
if (Controls) {
Screen.setFrame(4);
}
if (About) {
Screen.setFrame(5);
}
}
I would appreciate any advice on the matter.
First I think it would be better if you established a state for your game, rather than just using an increasing number of boolean values. Such as this:
public enum ScreenState { Title, HowToPlay, Controls, About }
private ScreenState currentScreen = ScreenState.Title;
private void actOnKeyStates(int k) {
if ((k & DOWN) != 0) {
currentScreen = ScreenState.HowToPlay;
}
if ((k & UP) != 0) {
currentScreen = ScreenState.Controls;
}
if ((k & LEFT) != 0) {
currentScreen = ScreenState.Title;
}
if ((k & FIRE_PRESSED) != 0) {
currentScreen = ScreenState.About;
}
update();
}
public void update() {
switch(currentScreen) {
case Title:
Screen.setFrame(0);
break;
case HowToPlay:
Screen.setFrame(1);
break;
case Controls:
Screen.setFrame(4);
break;
case About:
Screen.setFrame(5);
break;
}
}
The second thing you need to do is confirm that k & DOWN is being executed correctly when the DOWN arrow is pressed. Also confirm that the image you are looking for is correctly placed in the position 1 in your sprite sheet.

Categories