Tic Tac Toe Client Server Interaction - java

I am currently trying to code a Tic Tac Toe game in Java that is playable across networks. I'm using socket programming in Java and for the UI I am using JavaFX. Upon launching the server and 2 clients, the client connects to the server, pairs players and creates the game. When trying to execute the actual Tic Tac Toe game the GUI gets stuck. I believe it may have something to do with threading but after countless hours of trying different solutions I haven't been able to figure it out.
Below is a video of the issue
https://www.youtube.com/watch?v=dCIxRkGJlCI&t=2s
My GitHub Repo:
https://github.com/Stinny/Tic-Tac-Toe
The issue I believe resides in the TicTacToeController.java class
Any info would be greatly appreciated!
This is my TicTacToeController Class
public class TicTacToeController implements Initializable {
private static Socket socket;
private static PrintWriter out;
private static BufferedReader in;
private static Image Circle = new Image("./Circle.png");
private static Image Cross = new Image("./Cross.png");
private static ImageView icon, opponentIcon;
#FXML
Button topLeft, topRight, topCenter,
midLeft, midCenter, midRight,
botLeft, botMid, botRight;
#FXML
Button play;
public void initialize(URL url, ResourceBundle rb) {
}
public void buttonClickHandler(ActionEvent evt) throws Exception{
Button clickedButton = (Button) evt.getTarget();
evt.getEventType();
String button =((Control)evt.getSource()).getId();
System.out.println(button);
if(button.equals("play")){
clickedButton.setDisable(true);
play();
}
else if (button.equals("topLeft")) {
out.print("MOVE0");
//do something
} else if (button.equals("topRight")) {
//do something
out.print("MOVE2");
} else if (button.equals("topCenter")) {
//do something
out.print("MOVE1");
} else if (button.equals("midLeft")) {
//do something
out.print("MOVE3");
} else if (button.equals("midCenter")) {
//do something
out.print("MOVE4");
} else if (button.equals("midRight")) {
//do something
out.print("MOVE5");
} else if (button.equals("botLeft")) {
//do something
out.print("MOVE6");
} else if (button.equals("botMid")) {
//do something
out.print("MOVE7");
} else if (button.equals("botRight")) {
//do something
out.print("MOVE8");
}
}
public void play() throws IOException {
String response;
try {
connectToServer();
response = in.readLine();
System.out.println("Send to server" + in);
char mark = response.charAt(7);
System.out.println("You are " + mark);
if (mark == 'X') {
icon = new ImageView(Circle);
opponentIcon = new ImageView(Cross);
} else {
icon = new ImageView(Cross);
opponentIcon = new ImageView(Circle);
}
//frame.setTitle("Tic Tac Toe - Player " + mark);
while (true) {
response = in.readLine();
if (response != null) {
System.out.println(response);
if (response.startsWith("VALID_MOVE")) {
int location = Integer.parseInt(response.substring(5));
if (location == 0) {
handleButtonClick(topLeft, icon);
} else if (location == 1) {
handleButtonClick(topLeft, icon);
} else if (location == 2) {
handleButtonClick(topLeft, icon);
} else if (location == 3) {
handleButtonClick(topLeft, icon);
} else if (location == 4) {
handleButtonClick(topLeft, icon);
} else if (location == 5) {
handleButtonClick(topLeft, icon);
} else if (location == 6) {
handleButtonClick(topLeft, icon);
} else if (location == 7) {
handleButtonClick(topLeft, icon);
} else if (location == 7) {
handleButtonClick(topLeft, icon);
} else if (location == 8) {
handleButtonClick(topLeft, icon);
}
} else if (response.startsWith("OPPONENT_MOVED")) {
int location = Integer.parseInt(response.substring(15));
if (location == 0) {
handleButtonClick(topLeft, opponentIcon);
} else if (location == 1) {
handleButtonClick(topCenter, opponentIcon);
} else if (location == 2) {
handleButtonClick(topRight, opponentIcon);
} else if (location == 3) {
handleButtonClick(midLeft, opponentIcon);
} else if (location == 4) {
handleButtonClick(midCenter, opponentIcon);
} else if (location == 5) {
handleButtonClick(midRight, opponentIcon);
} else if (location == 6) {
handleButtonClick(botLeft, opponentIcon);
} else if (location == 7) {
handleButtonClick(botMid, opponentIcon);
} else if (location == 8) {
handleButtonClick(botRight, opponentIcon);
}
} else if (response.startsWith("VICTORY")) {
//messageLabel.setText("You win");
break;
} else if (response.startsWith("DEFEAT")) {
//messageLabel.setText("You lose");
break;
} else if (response.startsWith("TIE")) {
//messageLabel.setText("You tied");
break;
}
}
}
out.println("QUIT");
}
finally {
socket.close();
}
}
public void handleButtonClick(Button button, ImageView mark){
button.setGraphic(mark);
}
public static void connectToServer(){
try {
socket = new Socket("localhost", 7777);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println(e + " fuck");
}
}
}
This is my server class:
public class Server {
private static ServerSocket serverSocket;
private static ArrayList<Socket> sockets;
private static Socket socket;
public static void main(String[] args) throws Exception {
try {
serverSocket = new ServerSocket(7777);
sockets = new ArrayList<>();
for(int i = 1; i < 3; i++){
socket = serverSocket.accept();
System.out.println("Player " + i + " connected");
sockets.add(socket);
}
Game game = new Game();
System.out.println("Created game, waiting for players to connect");
Game.PlayerHandler playerX = game.new PlayerHandler(sockets.remove(sockets.size()-1), 'X');
Game.PlayerHandler playerO = game.new PlayerHandler(sockets.remove(sockets.size()-1), 'O');
game.currentPlayer = playerX;
playerX.start();
playerO.start();
System.out.println("Game started");
}catch(IOException e)
{
e.printStackTrace();
}
}
}
class Game{
private PlayerHandler[] board = {
null, null, null,
null, null, null,
null, null, null
};
PlayerHandler currentPlayer;
public boolean isFull(){
for(int i = 0; i < board.length; i++) {
if(board[i] == null){
return false;
}
}
return true;
}
public boolean hasWinner() {
if (checkHorizontalWin() || checkVerticalWin() || checkDiagonalWin()) {
return true;
} else {
return false;
}
}
public boolean checkHorizontalWin() {
if (board[0] != null && board[0] == board[1] && board[0] == board[2]) {
return true;
} else if(board[3] != null && board[3] == board[4] && board[3] == board[5]) {
return true;
} else if(board[6] != null && board[6] == board[7] && board[6] == board[8]) {
return true;
} else {
return false;
}
}
public boolean checkVerticalWin() {
if (board[0] != null && board[0] == board[3] && board[0] == board[6]) {
return true;
} else if(board[1] != null && board[1] == board[4] && board[1] == board[7]) {
return true;
} else if(board[2] != null && board[2] == board[5] && board[2] == board[8]) {
return true;
} else {
return false;
}
}
public boolean checkDiagonalWin() {
if (board[0] != null && board[0] == board[4] && board[0] == board[8]) {
return true;
} else if (board[2] != null && board[2] == board[4] && board[2] == board[6]) {
return true;
} else {
return false;
}
}
public synchronized boolean move(PlayerHandler player, int location) { //A player moves based on their assigned Piece
System.out.println("Player moved at location " + location);
if(board[location]==null){
board[location] = player;
currentPlayer = currentPlayer.opponent;
currentPlayer.opponentMoved(location);
return true;
}
return false;
}
class PlayerHandler extends Thread{
char mark;
private String name;
private Socket socket;
PlayerHandler opponent;
BufferedReader in;
PrintWriter out;
public PlayerHandler(Socket socket, char mark) {
this.socket = socket;
this.mark = mark;
try{
// initialize input and output streams
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println("WELCOME" + mark);
} catch(IOException e){
}
}
public void setOpponent(PlayerHandler opponent){
this.opponent = opponent;
}
public void opponentMoved(int location){
out.println("OPPONENT_MOVED" + location);
out.println(
hasWinner() ? "DEFEAT" : isFull() ? "TIE" : "");
}
public void run() {
try {
if (mark == 'X') {
out.println("MESSAGE Your move");
}
while (true) {
String command = in.readLine();
if (command != null) {
if (command.startsWith("MOVE")) {
int location = Integer.parseInt(command.substring(5));
System.out.println(location);
if (move(this, location)) {
out.println("VALID_MOVE" + "location");
out.println(hasWinner() ? "VICTORY"
: isFull() ? "TIE"
: "");
} else {
out.println("MESSAGE ?");
}
}
}
}
}catch(IOException e) {
System.out.println("Player died: " + e);
} finally {
try {socket.close();} catch(IOException e){}
}
}
}
}

Related

Java graphics slow down after adding objects

I am still new to java and I've been trying to make a SpaceInvaders copy in Java's native graphics. I've finished the basic mechanics, however the game slows down significantly when the player or aliens shoot a bullet. I have tried to find out what was causing the game to slow down, but was unable to.
public class Board extends JPanel implements KeyListener,ActionListener{
Ship ship;
Alien[] row1 = new Alien[10];
Alien[] row2 = new Alien[10];
Alien[] row3 = new Alien[10];
private Timer timer;
int DELAY = 16;
boolean reachedend = false;
Bullet bullet;
int lives;
public Board() {
setBackground(Color.BLACK);
addKeyListener(this);
lives = 3;
ship = new Ship();
fillAliens();
timer = new Timer(DELAY, this);
timer.start();
}
void fillAliens() {
for(int x=1;x<11;x++) {
row1[x-1] = new Alien(x*30+40,30);
row2[x-1] = new Alien(x*30+40,70);
row3[x-1] = new Alien(x*30+40,110);
}
}
void shoot() {
if(bullet==null) {
bullet = new Bullet(ship.x + ship.width/2,ship.y - ship.height/2,-1);
}
}
void drawAliens(Graphics2D g) {
g.setColor(Color.red);
for(int x=1;x<11;x++) {
if(row1[x-1].alive == true) {
g.fillRect(row1[x-1].x_loc, row1[x-1].y_loc, row1[x-1].width, row1[x-1].width);
}
if(row2[x-1].alive == true) {
g.fillRect(row2[x-1].x_loc, row2[x-1].y_loc, row2[x-1].width, row2[x-1].width);
}
if(row3[x-1].alive == true) {
g.fillRect(row3[x-1].x_loc, row3[x-1].y_loc, row3[x-1].width, row2[x-1].width);
}
}
}
public void addNotify() {
super.addNotify();
requestFocus();
}
void drawShip(Graphics2D g) {
g.fillRect(ship.x, ship.y, ship.width, ship.height);
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(lives>0) {
if (key == KeyEvent.VK_SPACE) {
shoot();
}
if (key == KeyEvent.VK_LEFT) {
if(ship.x>=5) {
ship.x -= 5;
}
}
if (key == KeyEvent.VK_RIGHT) {
if(ship.x+ship.width<434) {
ship.x += 5;
}
}
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
drawShip(g2);
drawAliens(g2);
drawBullet(g2);
drawAlienBullet(g2);
drawLives(g2);
}
private void drawLives(Graphics2D g2) {
g2.setColor(Color.white);
g2.drawString("Lives:", 10, 300);
for(int x=1; x<=lives;x++) {
g2.fillRect(15*x+30, 290, 10, 10);
}
}
private void drawBullet(Graphics2D g2) {
g2.setColor(Color.GREEN);
if(bullet!=null) {
g2.fillRect(bullet.x_loc, bullet.y_loc, bullet.width, bullet.height);
}
}
private void drawAlienBullet(Graphics2D g2) {
g2.setColor(Color.BLUE);
for(int x=0;x<10;x++) {
if(row3[x].bullet != null) {
g2.fillRect(row3[x].bullet.x_loc, row3[x].bullet.y_loc, row3[x].bullet.width, row3[x].bullet.height);
}
if(row2[x].bullet != null) {
g2.fillRect(row2[x].bullet.x_loc, row2[x].bullet.y_loc, row2[x].bullet.width, row2[x].bullet.height);
}
if(row1[x].bullet != null ) {
g2.fillRect(row1[x].bullet.x_loc, row1[x].bullet.y_loc, row1[x].bullet.width, row1[x].bullet.height);
}
}
}
private void bulletHitPlayer() {
for(int x=0;x<10;x++) {
if(row3[x].bullet != null) {
if(row3[x].bullet.y_loc >= 350) {
row3[x].bullet = null;
break;
}
}
if(row2[x].bullet != null) {
if(row2[x].bullet.y_loc >= 350) {
row2[x].bullet = null;
break;
}
}
if(row1[x].bullet != null) {
if(row1[x].bullet.y_loc >= 350) {
row1[x].bullet = null;
break;
}
}
if(row3[x].bullet != null && row3[x].bullet.y_loc + 10 >= ship.y && row3[x].bullet.y_loc <= ship.y + ship.height && row3[x].bullet.x_loc >= ship.x && row3[x].bullet.x_loc <= ship.x+ship.width) {
row3[x].bullet = null;
lives--;
break;
}
if(row2[x].bullet != null && row2[x].bullet.y_loc + 10 >= ship.y && row2[x].bullet.y_loc <= ship.y + ship.height && row2[x].bullet.x_loc >= ship.x && row2[x].bullet.x_loc <= ship.x+ship.width) {
row2[x].bullet = null;
lives--;
break;
}
if(row1[x].bullet != null && row1[x].bullet.y_loc + 10 >= ship.y && row1[x].bullet.y_loc <= ship.y + ship.height && row1[x].bullet.x_loc >= ship.x && row1[x].bullet.x_loc <= ship.x+ship.width) {
row1[x].bullet = null;
lives--;
break;
}
}
}
private void bulletHit() {
if(bullet!=null) {
for(int x=0;x<10;x++) {
if(row3[x].alive == true && bullet.y_loc >= row3[x].y_loc && bullet.y_loc <= row3[x].y_loc+row3[x].width && bullet.x_loc >= row3[x].x_loc && bullet.x_loc <= row3[x].x_loc+row3[x].width) {
row3[x].alive = false;
bullet=null;
break;
}
if(row2[x].alive == true && bullet.y_loc >= row2[x].y_loc && bullet.y_loc <= row2[x].y_loc+row2[x].width && bullet.x_loc >= row2[x].x_loc && bullet.x_loc <= row2[x].x_loc+row2[x].width) {
row2[x].alive = false;
bullet=null;
break;
}
if(row1[x].alive == true && bullet.y_loc >= row1[x].y_loc && bullet.y_loc <= row1[x].y_loc+row1[x].width && bullet.x_loc >= row1[x].x_loc && bullet.x_loc <= row1[x].x_loc+row1[x].width) {
row1[x].alive = false;
bullet=null;
break;
}
}
}
if(bullet!=null) {
if(bullet.y_loc<0) {
bullet=null;
}
}
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void actionPerformed(ActionEvent e) {
bulletHitPlayer();
bulletHit();
repaint();
}
}
Problem:
You draw your scene, whenever you press a key; and you draw your scene once on startup (see API and Tutorials) - But you should continuously redraw your scene by using the Timer properly.
How to solve:
When you create your Timer let it
either repeat itself timer.setRepeats(true);
or restart the Timer manually:
public void actionPerformed(ActionEvent e) {
bulletHitPlayer();
bulletHit();
repaint();
timer.restart(); //manually restart the timer
}

Java Maze Solver - Stack does not pop when pop() is called

I'm working on an assignment where I have to solve a maze through backtracking (using a stack!) and the logic of the code is basically done, but the main problem is whenever I call pop() on my stack, it does not pop.So for now I have manually added (hardcoded) the parts in the maze where it is supposed to pop(). I am using my own stack that is using Linked Nodes and have ran JUnit and Main tests and it does indeed work (doubting myself here now). I have also used the Java stack and I get the same result.
Here is my code logic: As you can see in the method mazeSolver, at the bottom, I have a few if statements that check if i (operations performed) is at a certain point and it will "backtrack", but I am manually setting the position. The very last else statement is the part where I pop(). Any help would very much be appreciated.
public class MazeSolver {
private char[][] printMaze;
private char[][] solveMaze;
public MazeSolver() {
super();
}
private class Position {
private int x;
private int y;
Position(int y, int x) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
public boolean solve(boolean printUpdates) {
char space = ' ';
Stack<Position> stack = new Stack<Position>();
//Stack stack = new Stack();
Position cp = new Position(1, 0);
boolean done = true;
char c = 'C';
char x = 'X';
int i = 0;
while (done) {
// check right
if (printMaze[cp.getY()][cp.getX() + 1] == space && printMaze[cp.getY()][cp.getX() + 1] != x) {
cp.setX(cp.getX() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check bottom
else if (printMaze[cp.getY() + 1][cp.getX()] == space && printMaze[cp.getY() + 1][cp.getX()] != x
&& printMaze[cp.getY() + 1][cp.getX()] != x) {
cp.setY(cp.getY() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check top
else if (printMaze[cp.getY() - 1][cp.getX()] == space && printMaze[cp.getY() - 1][cp.getX()] != x) {
cp.setY(cp.getY() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check left
else if (printMaze[cp.getY()][cp.getX() - 1] == space && printMaze[cp.getY()][cp.getX() - 1] != x) {
cp.setX(cp.getX() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
//else {
/*
if (i == 6) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(5);
} else if (i == 27) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(20);
}
else if (i == 37) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(2);
cp.setX(18);
}
else if (i == 68) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(13);
cp.setX(22);
} else if (i == 69) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(14);
cp.setX(22);
}
else if (i == 70) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(15);
cp.setX(22);
} else if (i == 71) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(16);
cp.setX(22);
} else if (i == 72) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(17);
cp.setX(22);
} else if (i == 103) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(21);
cp.setX(31);
} */else {
printMaze[cp.getY()][cp.getX()] = 'X';
stack.pop();
cp.setY(((Position) stack.top()).getY());
cp.setX(((Position) stack.top()).getX());
}
//}
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println(stack.top().getX() + ", " + stack.top().getY());
System.out.println(cp.getY() + ", " + cp.getX() + " i = " + i);
printMaze();
}
System.out.println("success");
return false;
}
public void printMaze() {
for (int i = 0; i < printMaze.length; i++) {
for (int j = 0; j < printMaze[i].length; j++) {
System.out.print(printMaze[i][j]);
}
System.out.println("");
}
}
public boolean loadMaze(String filename) {
BufferedReader br = null;
FileReader fr = null;
ArrayList<String> lines = new ArrayList<String>();
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
lines.add(line);
}
printMaze = new char[lines.size()][];
solveMaze = new char[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
printMaze[i] = new char[lines.get(i).length()];
solveMaze[i] = new char[lines.get(i).length()];
for (int j = 0; j < lines.get(i).length(); j++) {
solveMaze[i][j] = lines.get(i).charAt(j);
printMaze[i][j] = lines.get(i).charAt(j);
if (solveMaze[i][j] == 'S') {
// hint you need to do this but you do not have the
// instance variable yet
// start = new Position(i, j);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
return false;
}
}
return true;
}
Here is my stack implementation if interested.
public class Stack<Item> implements StackInterface<Item> {
private int size;
private class Link {
private Item data;
public Link next;
public Link(Item data, Link next) {
this.data = data;
this.next = next;
}
public Item getData() {
return data;
}
}
private Link topStackLink = null;
public Stack() {
this.size = 0;
}
#Override
public void push(Item item) {
if (topStackLink == null) {
topStackLink = new Link(item, null);
} else {
topStackLink = new Link(item, topStackLink);
}
this.size++;
}
#Override
public void pop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
topStackLink = topStackLink.next;
this.size--;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item top() {
if (topStackLink != null) {
return topStackLink.data;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item topAndPop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
Item item = topStackLink.data;
pop();
return item;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public boolean isEmpty() {
if (topStackLink == null) {
return true;
} else {
return false;
}
}
#Override
public void makeEmpty() {
// TODO Auto-generated method stub
topStackLink = null;
this.size = 0;
}
#Override
public int size() {
return this.size;
}

Prevent Array List Overlap?

I am creating a Binding of Isaac-esque Roguelike that is generated using an Array List using four Booleans. The four Booleans being North, East, South, and West. Corresponding to which doors is open.
The problem with Array Lists is that it can 'overlap'. For example, if I go east, than south, than west, than north, I'll be in a whole new room, and not the original.
Is there a way to stop this from happening, or at least prevent it? Such as if the room above room 1 (room 2) has south set to true, than north will be true in room 1 to connect the two rooms. Or if room 2 has south set to false, than north will be false in room 1 to stop overlap.
Here is my current code (I know my code isn't exactly clean and has a lot of magic numbers, but those shouldn't be important for this question)-
GameState:
public class GameState extends JFrame implements KeyListener {
Container contentPane=this.getContentPane();
Graphics bufferGraphics;
int characterX=463;
int characterY=486;
int oldCharacterX=463;
int oldCharacterY=486;
int xAxis;
int yAxis;
int minimapX=1300;
int minimapY=515;
Image characterNorth = CustomImages.createImageIcon("Images/characterNorth.jpg").getImage();
Image characterEast = CustomImages.createImageIcon("Images/characterEast.jpg").getImage();
Image characterSouth = CustomImages.createImageIcon("Images/characterSouth.jpg").getImage();
Image characterWest = CustomImages.createImageIcon("Images/characterWest.jpg").getImage();
Image brickWall = CustomImages.createImageIcon("Images/brickWall.jpg").getImage();
Image brickFloor = CustomImages.createImageIcon("Images/brickFloor.jpg").getImage();
Image character=characterNorth;
boolean pressed=false;
boolean minimap=true;
ArrayList<RoomState> map = new ArrayList<RoomState>();
RoomState currentRoom = new RoomState();
RoomState currentRoomState=new RoomState();
GameState() {
this.setBounds(0, 0, 1680, 1050);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void move(int x, int y) { //Check Move
currentRoomState=currentRoomState.MoveToNextRoom(true, false, false, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, true, false, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, false, true, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, false, false, true);
}
public void paint(Graphics g) { //Graphics
for(xAxis=58;xAxis<=858;xAxis=xAxis+50) {
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickFloor,xAxis,yAxis,null);
}
yAxis=31;
}
for(xAxis=8;xAxis<958;xAxis=xAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
yAxis=931;
for(xAxis=8;xAxis<=908;xAxis=xAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
xAxis=8;
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
xAxis=908;
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
if(currentRoom.northDoor) {
g.drawImage(brickFloor,458,31,null);
}
if(currentRoom.eastDoor) {
g.drawImage(brickFloor,908,481,null);
}
if(currentRoom.southDoor) {
g.drawImage(brickFloor,458,931,null);
}
if(currentRoom.westDoor) {
g.drawImage(brickFloor,8,481,null);
}
g.drawImage(character,characterX,characterY,null);
g.drawString("[ ]",minimapX,minimapY);
g.setColor(Color.RED);
g.drawString("[ ]", 1300, 515);
}
#Override
public void keyPressed(KeyEvent arg0) { //Character Rotation/Movement.
if(pressed==false) {
pressed=true;
oldCharacterX=characterX;
oldCharacterY=characterY;
if(arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_UP) {
if(character==characterNorth) {
if(characterY>86 && characterX>13 && characterX<913) {
characterY=characterY-50;
}else if(currentRoom.northDoor && characterX==463) {
oldCharacterY=characterY;
characterY=characterY-50;
if(characterY==-14) {
if(currentRoom.rs_NorthDoor != null) {
currentRoom=currentRoom.rs_NorthDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, false, true, false);
currentRoom.rs_NorthDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapY=minimapY-10;
characterX=463;
characterY=936;
repaint();
}
}
}else {
character=characterNorth;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_LEFT) {
if(character==characterWest && characterY>36 && characterY<926) {
if(characterX>63) {
oldCharacterX=characterX;
characterX=characterX-50;
}else if(currentRoom.westDoor && characterY==486) {
oldCharacterX=characterX;
characterX=characterX-50;
if(characterX==-37) {
if(currentRoom.rs_WestDoor != null) {
currentRoom = currentRoom.rs_WestDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, true, false, false);
currentRoom.rs_WestDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapX=minimapX-8;
characterX=913;
characterY=486;
repaint();
}
}
}else {
character=characterWest;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if(character==characterSouth) {
if(characterY<871 && characterX>13 && characterX<913) {
oldCharacterY=characterY;
characterY=characterY+50;
}else if(currentRoom.southDoor && characterX==463) {
oldCharacterY=characterY;
characterY=characterY+50;
if(characterY==986) {
if(currentRoom.rs_SouthDoor != null) {
currentRoom=currentRoom.rs_SouthDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,true, false, false, false);
currentRoom.rs_SouthDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapY=minimapY+10;
characterX=463;
characterY=36;
repaint();
}
}
}else {
character=characterSouth;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_D || arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
if(character==characterEast && characterY>36 && characterY<926) {
if(characterX<848) {
oldCharacterX=characterX;
characterX=characterX+50;
}else if(currentRoom.eastDoor && characterY==486) {
oldCharacterX=characterX;
characterX=characterX+50;
if(characterX==963) {
if(currentRoom.rs_EastDoor != null) {
currentRoom = currentRoom.rs_EastDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, false, false, true);
currentRoom.rs_EastDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapX=minimapX+8;
characterX=13;
characterY=486;
repaint();
}
}
}else {
character=characterEast;
}
}
if(oldCharacterX != characterX || oldCharacterY != characterY) {
repaint(oldCharacterX,oldCharacterY,40,40);
}
repaint(characterX,characterY,40,40);
}
}
#Override
public void keyReleased(KeyEvent arg0) { //Prevents Holding Down Keys.
if(arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_UP) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_LEFT) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_D || arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
pressed=false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
RoomState:
public class RoomState {
boolean northDoor;
boolean eastDoor;
boolean southDoor;
boolean westDoor;
boolean doorsOpen;
int northRoll;
int eastRoll;
int southRoll;
int westRoll;
Random r=new Random();
//Reference to the adjacent rooms
RoomState rs_NorthDoor=null;
RoomState rs_EastDoor=null;
RoomState rs_SouthDoor=null;
RoomState rs_WestDoor=null;
RoomState() { //Initial
while(!doorsOpen) {
northRoll=r.nextInt(6)+1;
eastRoll=r.nextInt(6)+1;
southRoll=r.nextInt(6)+1;
westRoll=r.nextInt(6)+1;
if(northRoll==1) {
northDoor=true;
}else {
northDoor=false;
}
if(eastRoll==1) {
eastDoor=true;
}else {
eastDoor=false;
}
if(southRoll==1) {
southDoor=true;
}else {
southDoor=false;
}
if(westRoll==1) {
westDoor=true;
}else {
westDoor=false;
}
if(northDoor==false && eastDoor==false && southDoor==false && westDoor==false) {
doorsOpen=false;
}else {
doorsOpen=true;
}
}
}
RoomState(RoomState previousState, boolean north, boolean east, boolean south, boolean west) {
this();
if(north) {
rs_NorthDoor=previousState;
northDoor=true;
}else if(east) {
rs_EastDoor=previousState;
eastDoor=true;
}else if(south) {
rs_SouthDoor=previousState;
southDoor=true;
}else if(west) {
rs_WestDoor=previousState;
westDoor=true;
}
}
public RoomState MoveToNextRoom(boolean north, boolean east, boolean south, boolean west) {
if(north) {
if(rs_NorthDoor==null) {
rs_NorthDoor=new RoomState(this,north,east,south,west);
}
return rs_NorthDoor;
}
if(east) {
if(rs_EastDoor==null) {
rs_EastDoor=new RoomState(this,north,east,south,west);
}
return rs_EastDoor;
}
if(south) {
if(rs_SouthDoor==null) {
rs_SouthDoor=new RoomState(this,north,east,south,west);
}
return rs_SouthDoor;
}
if(west) {
if(rs_WestDoor==null) {
rs_WestDoor=new RoomState(this,north,east,south,west);
}
return rs_WestDoor;
}
return null;
}
}

Java Gett variable from within a loop in another class?

I was wondering how it is possible to get the value of a variable/boolean that is inside of a loop in a different class.
I would have a variable in one class and want get that in another one:
Class1:
public void mainLoop()
{
while(!Display.isCloseRequested)
{
frames++
if(frames == 200)
{
key = 5
run = false;
}
if(frames == 400)
{
key = 10
run = true;
}
}
}
and in my other Class2 I want to acess the changed varibles:
public Class2()
{
public void printVariables(int key)
{
if(key == 5) { System.out.println("KEY 5"); }
if(key == 10) { System.out.println("KEY 10"); }
if(run == false) { System.out.println("RUN FALSE"); }
if(run == true) { System.out.println("RUN TRUE"); }
}
}
How?
Thanks for any Help!
Add it as a parameter to the method:
public Class2()
{
public void printVariables(int key)
{
if(key == 5) { System.out.println("KEY 5"); }
if(key == 10) { System.out.println("KEY 10"); }
if(run == false) { System.out.println("RUN FALSE"); }
if(run == true) { System.out.println("RUN TRUE"); }
}
}
And then call that method with an instance of the class:
public void mainLoop()
{
Class2 cls2 = new Class2();
while(someCondition == true)
{
frames++
if(frames == 200)
{
key = 5
run = false;
}
if(frames == 400)
{
key = 10
run = true;
}
cls2.printVariables(key);
}
}
Or, if you can, make the method static and call it statically (i.e. Class2.printVariables(key)).

AVL tree in java

The program that I am writing simulates a road charging system which reads several lines of inputs, each one representing a different command until I reach the EOF (\n).
This commands simulate a road charging system, where the input reads as follows:
PASS 44AB55 I -> where the first word is the command the program receives, the second word is the number plate of the car (44AB55) and the second is the status of the car (Regular or Irregular).
There are three types of commands:
“PASS 00AA00 R” – Increments the number of times that the car has passed in the system and marks its status has Regular or Irreguar. If the car isnt still in the database, it inserts the car as Regular and starts the counter with one passage.
“UNFLAG 00AA00” – Flags the car as Regular if it exists in the database. If the car doesnt exist in the database ignores the command.
“STATUS 00AA00” – Retrieves the status of the car (Regular or Irregular) and the number of passages of the car in the system. If it the car doesnt exist in the database, prints a "NO RECORD" message.
To solve this problem, I am using AVL trees and using the following code:
import java.util.ArrayList;
import java.util.Scanner;
public class TP2_probB {
static No raiz = null;
static double numRotacoes = 0;
static double numAtravessos = 0;
public static class No {
private String matricula;
private int porticos;
private boolean estadoRegular;
private No pai;
private No filhoEsq;
private No filhoDir;
private int balanco;
public No(String matricula, int porticos, boolean estadoRegular) {
this.matricula = matricula;
this.porticos = porticos;
this.estadoRegular = estadoRegular;
this.pai = null;
this.filhoDir = null;
this.filhoEsq = null;
this.balanco = 0;
}
public void setEstadoRegular(boolean estadoRegular) {
this.estadoRegular = estadoRegular;
}
public void setPai(No pai) {
this.pai = pai;
}
public void setFilhoEsq(No filhoEsq) {
this.filhoEsq = filhoEsq;
}
public void setFilhoDir(No filhoDir) {
this.filhoDir = filhoDir;
}
public void atribuiNoEsq(No noEsq) {
this.filhoEsq = noEsq;
}
public void atribuiNoDir(No noDir) {
this.filhoDir = noDir;
}
public void atribuiPai(No noPai) {
this.pai = noPai;
}
public void aumentaPortico() {
porticos++;
}
public String getMatricula() {
return matricula;
}
public boolean isEstadoRegular() {
return estadoRegular;
}
public No getPai() {
return pai;
}
public No getFilhoEsq() {
return filhoEsq;
}
public No getFilhoDir() {
return filhoDir;
}
#Override
public String toString() {
String estado;
if (estadoRegular == true) {
estado = "R";
} else {
estado = "I";
}
return matricula + " " + porticos + " " + estado;
}
}
public static No duplaRotacaoFilhoEsq(No k3)
{
k3.filhoEsq = rotacaoFilhoDir(k3);
return rotacaoFilhoEsq(k3);
}
public static No duplaRotacaoFilhoDir(No k3)
{
k3.filhoDir = rotacaoFilhoEsq(k3);
return rotacaoFilhoDir(k3);
}
public static No rotacaoFilhoDir(No k1) {
No k2 = k1.filhoDir;
k2.pai=k1.pai;
k1.filhoDir = k2.filhoEsq;
if(k1.filhoDir!=null)
{
k1.filhoDir.pai=k1;
}
k2.filhoEsq = k1;
k1.pai=k2;
if(k2.pai!=null)
{
if(k2.pai.filhoDir==k1)
{
k2.pai.filhoDir = k2;
}
else if(k2.pai.filhoEsq==k1)
{
k2.pai.filhoEsq = k2;
}
}
balanco(k2);
balanco(k1);
return k2;
}
public static No rotacaoFilhoEsq(No k1) {
No k2 = k1.filhoEsq;
k2.pai=k1.pai;
k1.filhoEsq = k2.filhoDir;
if(k1.filhoEsq!=null)
{
k1.filhoEsq.pai=k1;
}
k2.filhoDir = k1;
k1.pai=k2;
if(k2.pai!=null)
{
if(k2.pai.filhoDir==k1)
{
k2.pai.filhoDir = k2;
}
else if(k2.pai.filhoEsq==k1)
{
k2.pai.filhoEsq = k2;
}
}
balanco(k2);
balanco(k1);
return k2;
}
public static int pesagem(No aux)
{
if(aux==null)
{
return -1;
}
if(aux.filhoEsq == null && aux.filhoDir == null)
{
return 0;
}
else if ((aux.filhoEsq == null))
{
return (pesagem(aux.filhoDir) + 1);
}
else if ((aux.filhoDir == null))
{
return (pesagem(aux.filhoEsq) + 1);
}
else
return (Math.max(pesagem(aux.filhoEsq), pesagem(aux.filhoDir)) + 1);
}
public static void balanco(No tmp)
{
tmp.balanco = pesagem(tmp.filhoDir)-pesagem(tmp.filhoEsq);
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String linha;
String[] aux;
ArrayList<String> output = new ArrayList<String>();
int x = 0;
while (true) {
linha = input.nextLine();
if (linha.isEmpty())
{
break;
}
else
{
aux = linha.split(" ");
if (aux[0].compareTo("PASS") == 0) {
No novo;
if (aux[2].compareTo("R") == 0) {
novo = new No(aux[1], 1, true);
} else {
novo = new No(aux[1], 1, false);
}
if (raiz == null) {
raiz = novo;
balanco(raiz);
} else {
procuraNo(novo);
}
} else if (aux[0].compareTo("UNFLAG") == 0) {
if (raiz != null) {
No no = new No(aux[1], 0, false);
mudaEstado(no);
}
} else if (aux[0].compareTo("STATUS") == 0) {
if (raiz == null) {
output.add(aux[1] + " NO RECORD");
} else {
No no = new No(aux[1], 0, false);
output.add(procuraRegisto(no));
}
}
}
}
for (int i = 0; i < output.size(); i++) {
System.out.println(output.get(i));
}
System.out.println("Número de Rotações: "+numRotacoes+"\nNúmero de atravessias: "+numAtravessos);
}
public static void procuraNo(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
aux.aumentaPortico();
aux.setEstadoRegular(novo.isEstadoRegular());
equilibra(aux);
break;
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
novo.setPai(aux);
aux.setFilhoDir(novo);
aux=aux.filhoDir;
equilibra(aux);
break;
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
novo.setPai(aux);
aux.setFilhoEsq(novo);
aux=aux.filhoEsq;
equilibra(aux);
break;
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
public static void equilibra(No tmp) {
balanco(tmp);
int balanco = tmp.balanco;
System.out.println(balanco);
if(balanco==-2)
{
if(pesagem(tmp.filhoEsq.filhoEsq)>=pesagem(tmp.filhoEsq.filhoDir))
{
tmp = rotacaoFilhoEsq(tmp);
numRotacoes++;
System.out.println("Rodou");
}
else
{
tmp = duplaRotacaoFilhoDir(tmp);
numRotacoes++;
System.out.println("Rodou");
}
}
else if(balanco==2)
{
if(pesagem(tmp.filhoDir.filhoDir)>=pesagem(tmp.filhoDir.filhoEsq))
{
tmp = rotacaoFilhoDir(tmp);
numRotacoes++;
System.out.println("Rodou");
}
else
{
tmp = duplaRotacaoFilhoEsq(tmp);
numRotacoes++;
System.out.println("Rodou");
}
}
if(tmp.pai!=null)
{
equilibra(tmp.pai);
}
else
{
raiz = tmp;
}
}
public static void mudaEstado(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
aux.setEstadoRegular(true);
break;
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
break;
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
break;
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
public static String procuraRegisto(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
return aux.toString();
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
return (novo.getMatricula() + " NO RECORD");
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
return (novo.getMatricula() + " NO RECORD");
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
}
The problem is that I am getting a stack overflow error:
Exception in thread "main" java.lang.StackOverflowError
at TP2_probB.pesagem(TP2_probB.java:174)
at TP2_probB.pesagem(TP2_probB.java:177)
at TP2_probB.pesagem(TP2_probB.java:177)
at TP2_probB.pesagem(TP2_probB.java:177)
(...)
at TP2_probB.pesagem(TP2_probB.java:177)
Here is a link with two files with inputs used to test the program:
https://drive.google.com/folderview?id=0B3OUu_zQ9xlGfjZHRlp6QkRkREc3dU82QmpSSWNMRlBuTUJmWTN5Ny1LaDhDN3M2WkVjYVk&usp=sharing

Categories