简体   繁体   中英

While loop causing issues with updating JTextField [on hold]

So, the code is intended to be a simple game that uses characters to represent things, but when either ac(Cat) or ab(Bat) is hit, the game freezes and the JTextField doesn't update correctly. I narrowed the issue down to the while loop but I cant understand why it doesn't work. Here is my code -

import java.util.ArrayList;
import java.io.*;
import java.lang.reflect.*;
import java.lang.Math;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Main {
  public static int posX = 9;
  public static int posY = 5;
  public static int posXPast = 9;
  public static int posYPast = 5;
  public static int cposXPast = 9;
  public static int cposYPast = 5;
  public static int chance = 99;
  public static int cTamed = 0;
  public static String row1 = "";
  public static String row2 = "";
  public static String row3 = "";
  public static String row4 = "";
  public static String row5 = "";
  public static String row6 = "";
  public static String row7 = "";
  public static String row8 = "";
  public static String row9 = "";
  public static String row10 = "";
  public static String row11 = "";
  public static boolean upTest = false;
  public static boolean downTest = false;
  public static boolean leftTest = false;
  public static boolean rightTest = false;
  public static int testOne = 0;
  public static int testTwo = 0;
  public static int testThree = 0;
  public static boolean enterTest = false;
  public static JTextField row1L = new JTextField();
  public static JTextField row2L = new JTextField();
  public static JTextField row3L = new JTextField();
  public static JTextField row4L = new JTextField();
  public static JTextField row5L = new JTextField();
  public static JTextField row6L = new JTextField();
  public static JTextField row7L = new JTextField();
  public static JTextField row8L = new JTextField();
  public static JTextField row9L = new JTextField();
  public static JTextField row10L = new JTextField();
  public static JTextField row11L = new JTextField();
  public static JTextField output = new JTextField();
  public static JTextField output2 = new JTextField();
  public static String[] set = new String[0];
  public static CreateReadOnlyJTextField CreateReadOnlyJTextField = new CreateReadOnlyJTextField();
  public static MKeyListener MKeyListener = new MKeyListener();
  public static String saveName = "test1.sav";
  public static String [] [] board = new String [11] [11];
  public static void boardInit() {
    for (int i = 0; i < 11; i++) {
      for (int a = 0; a < 11; a++) {
        board[i][a] = "   ";
      }
    }
    for (int tRow = 0; tRow < 11; tRow++) {
      board[0][tRow] = "x  ";
      board[tRow][0] = "x  ";
      board[10][tRow] = "x  ";
      board[tRow][10] = "x  ";
    }
    board [0] [5] = "   ";
    board [posX][posY] = "@  ";
    for (int r1 = 0; r1 < 11; r1++) {
        row1 += board[0][r1];
        row2 += board[1][r1];
        row3 += board[2][r1];
        row4 += board[3][r1];
        row5 += board[4][r1];
        row6 += board[5][r1];
        row7 += board[6][r1];
        row8 += board[7][r1];
        row9 += board[8][r1];
        row10 += board[9][r1];
        row11 += board[10][r1];
      }
    row1L.setText(row1);
    row2L.setText(row2);
    row3L.setText(row3);
    row4L.setText(row4);
    row5L.setText(row5);
    row6L.setText(row6);
    row7L.setText(row7);
    row8L.setText(row8);
    row9L.setText(row9);
    row10L.setText(row10);
    row11L.setText(row11);
  }
  public static void boardUpdate() {
    if (cTamed == 1) {
      board [posXPast][posYPast] = "c  ";
      board [cposXPast][cposYPast] = "   ";
      cposXPast = posXPast;
      cposYPast = posYPast;
    }else {
      board [posXPast][posYPast] = "   ";
    }
    board [posX][posY] = "@  ";
    posXPast = posX;
    posYPast = posY;
    row1 = "";
    row2 = "";
    row3 = "";
    row4 = "";
    row5 = "";
    row6 = "";
    row7 = "";
    row8 = "";
    row9 = "";
    row10 = "";
    row11 = "";
    for (int r1 = 0; r1 < 11; r1++) {
        row1 += board[0][r1];
        row2 += board[1][r1];
        row3 += board[2][r1];
        row4 += board[3][r1];
        row5 += board[4][r1];
        row6 += board[5][r1];
        row7 += board[6][r1];
        row8 += board[7][r1];
        row9 += board[8][r1];
        row10 += board[9][r1];
        row11 += board[10][r1];
      }
    row1L.setText(row1);
    row2L.setText(row2);
    row3L.setText(row3);
    row4L.setText(row4);
    row5L.setText(row5);
    row6L.setText(row6);
    row7L.setText(row7);
    row8L.setText(row8);
    row9L.setText(row9);
    row10L.setText(row10);
    row11L.setText(row11);
    mainRecall();
  }
  public static void mainRecall() {
    int levelFin = 0;
    if (posX == 0 && posY == 5) {
      levelFin = 1;
    }
    if (upTest == true) {
      upTest = false;
      if (posX > 0) {
        if(board[posX - 1][posY].equals("B  ")) {
          hitB(posX - 1, posY);
        }else if(board[posX - 1][posY].equals("*  ")) {
          hitStar(posX - 1, posY);
        }else if(board[posX - 1][posY].equals("C  ")) {
          hitC(posX - 1, posY);
        }else if(board[posX - 1][posY].equals("S  ")) {
          output2.setText("You hit a statue!");
          boardUpdate();
        }
      }
      if (levelFin == 1) {
        newLevel();
      }else {
        if (posX == 1 && posY != 5) {
          output2.setText("This path is blocked by a wall.");
        }else {
          posX--;
        }
        boardUpdate();
      }
    }
    else if (downTest == true) {
      downTest = false;
      if(board[posX + 1][posY].equals("B  ")) {
        hitB(posX + 1, posY);
      }else if(board[posX + 1][posY].equals("*  ")) {
        hitStar(posX + 1, posY);
      }else if(board[posX + 1][posY].equals("C  ")) {
        hitC(posX + 1, posY);
      }else if(board[posX + 1][posY].equals("S  ")) {
        output2.setText("You hit a statue!");
        boardUpdate();
      }else {
        if (posX == 9) {
          output2.setText("This path is blocked by a wall.");
        }else {
          posX++;
        }
        boardUpdate();
      }
    }else if (leftTest == true) {
      leftTest = false;
      if(board[posX][posY - 1].equals("B  ")) {
        hitB(posX, posY - 1);
      }else if(board[posX][posY - 1].equals("*  ")) {
        hitStar(posX, posY - 1);
      }else if(board[posX][posY - 1].equals("C  ")) {
        hitC(posX, posY - 1);
      }else if(board[posX][posY - 1].equals("S  ")) {
        output2.setText("You hit a statue!");
        boardUpdate();
      }else {
        if (posY == 1 || posX == 0) {
          output2.setText("This path is blocked by a wall.");
        }else {
          posY--;
        }
        boardUpdate();
      }
    }else if (rightTest == true) {
      rightTest = false;
      if(board[posX][posY + 1].equals("B  ")) {
        hitB(posX, posY + 1);
      }else if(board[posX][posY + 1].equals("*  ")) {
        hitStar(posX, posY + 1);
      }else if(board[posX][posY + 1].equals("C  ")) {
        hitC(posX, posY + 1);
      }else if(board[posX][posY + 1].equals("S  ")) {
        output2.setText("You hit a statue!");
        boardUpdate();
      }else {
        if (posY == 9 || posX == 0) {
          output2.setText("This path is blocked by a wall.");
        }else {
          posY++;
        }
        boardUpdate();
      }
    }else if (enterTest == true) {
      enterTest = false;
      try {
        FileOutputStream saveFile = new FileOutputStream(saveName);
        ObjectOutputStream save = new ObjectOutputStream(saveFile);
        save.writeObject(posX);
        save.writeObject(posY);
        save.writeObject(posXPast);
        save.writeObject(posYPast);
        save.writeObject(chance);
        save.writeObject(board);
        save.close();
      } catch (Exception exc) {
        exc.printStackTrace();
      }
    }
  }
  public static void newLevel (){
    chance--;
    posX = 9;
    posY = 5;
    posXPast = 9;
    posYPast = 5;
    for (int i = 0; i < 11; i++) {
      for (int a = 0; a < 11; a++) {
        board[i][a] = "   ";
      }
    }
    for (int tRow = 0; tRow < 11; tRow++) {
      board[0][tRow] = "x  ";
      board[tRow][0] = "x  ";
      board[10][tRow] = "x  ";
      board[tRow][10] = "x  ";
    }
    for (int i = 1; i < 10; i++) {
      for (int a = 1; a < 10; a++) {
        int rand = (int)(Math.random() * 101);
        if (rand > chance) {
          board[i][a] = "B  ";
        }
      }
    }
    for (int i = 1; i < 10; i++) {
      for (int a = 1; a < 10; a++) {
        int rand = (int)(Math.random() * 101);
        if (rand > chance) {
          board[i][a] = "C  ";
        }
      }
    }
    for (int i = 1; i < 10; i++) {
      for (int a = 1; a < 10; a++) {
        int rand = (int)(Math.random() * 101);
        if (rand > chance) {
          board[i][a] = "*  ";
        }
      }
    }
    board [0] [5] = "   ";
    board [posX][posY] = "@  ";
    row1 = "";
    row2 = "";
    row3 = "";
    row4 = "";
    row5 = "";
    row6 = "";
    row7 = "";
    row8 = "";
    row9 = "";
    row10 = "";
    row11 = "";
    for (int r1 = 0; r1 < 11; r1++) {
        row1 += board[0][r1];
        row2 += board[1][r1];
        row3 += board[2][r1];
        row4 += board[3][r1];
        row5 += board[4][r1];
        row6 += board[5][r1];
        row7 += board[6][r1];
        row8 += board[7][r1];
        row9 += board[8][r1];
        row10 += board[9][r1];
        row11 += board[10][r1];
      }
    row1L.setText(row1);
    row2L.setText(row2);
    row3L.setText(row3);
    row4L.setText(row4);
    row5L.setText(row5);
    row6L.setText(row6);
    row7L.setText(row7);
    row8L.setText(row8);
    row9L.setText(row9);
    row10L.setText(row10);
    row11L.setText(row11);
    mainRecall();
  }
  public static void hitC(int cPosX, int cPosY) {
    int tAttempted = 0;
    int jAttempted = 0;
    int bAttempted = 0;
    String tAttemptedI = "t";
    String jAttemptedI = "j";
    String bAttemptedI = "b";
    int counter = 1;
    int success = 0;
    String out = "Would you like to ";
    ArrayList<String> vars = new ArrayList<String>();
    output2.setText("You hit a cat!");
    while(success != 1) {
      if (tAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to tame it?";
        counter++;
        vars.add(tAttemptedI);
      }
      if (jAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to jump over it?";
        counter++;
        vars.add(jAttemptedI);
      }
      if (bAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to bait it away?";
        counter++;
        vars.add(bAttemptedI);
      }
      if (tAttempted + jAttempted + bAttempted == 3) {
        output2.setText("The cat turned into a statue...");
        board[cPosX][cPosY] = "S  ";
        success = 1;
        break;
      }
      output2.setText(out);
      if (testOne + testTwo + testThree > 3 - tAttempted + jAttempted + bAttempted || testOne + testTwo + testThree < 1 || testOne + testTwo + testThree > counter - 1) {
          testOne = 0;
          testTwo = 0;
          testThree = 0;
          output2.setText("Invalid response");
      }else if (vars.get((testOne + testTwo + testThree) - 1).equals("t")) {
        int seed = (int)(Math.random() * 101);
        if (seed > 50) {
          output2.setText("Success! The cat was tamed and will now follow you!");
          cTamed = 1;
          board[cPosX][cPosY] = "   ";
          success = 1;
        }else {
          output2.setText("Failed!"); 
          vars.remove((testOne + testTwo + testThree) - 1);
          tAttempted = 1;
        }
      }else if (vars.get((testOne + testTwo + testThree) - 1).equals("j")) {
        int seed2 = (int)(Math.random() * 101);
        if (seed2 > 50) {
          output2.setText("Success! You jumped over the cat and avoided it, but it is still there!");
          success = 1;
        }else {
          output2.setText("Failed!");
          vars.remove(testOne + testTwo + testThree - 1);
          jAttempted = 1;
        }
      }else if (vars.get((testOne + testTwo + testThree) - 1).equals("b")) {
        int seed3 = (int)(Math.random() * 101);
        if (seed3 > 50) {
          output2.setText("Success! You baited the cat away!");
          success = 1;
          board[cPosX][cPosY] = "   ";
        }else {
          output2.setText("Failed!");
          vars.remove(testOne + testTwo + testThree - 1);
          bAttempted = 1;
        }
      }
      counter = 1;
    }
    testOne = 0;
    testTwo = 0;
    testThree = 0;
    boardUpdate();
  }
  public static void hitB(int bPosX, int bPosY) {
    int tAttempted = 0;
    int jAttempted = 0;
    int bAttempted = 0;
    String tAttemptedI = "t";
    String jAttemptedI = "j";
    String bAttemptedI = "b";
    int counter = 1;
    int success = 0;
    String out = "Would you like to ";
    ArrayList<String> vars = new ArrayList<String>();
    output2.setText("You hit a bat!");
    while(success != 1) {
      if (tAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to tame it?";
        counter++;
        vars.add(tAttemptedI);
      }
      if (jAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to jump over it?";
        counter++;
        vars.add(jAttemptedI);
      }
      if (bAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to bait it away?";
        counter++;
        vars.add(bAttemptedI);
      }
      if (tAttempted + jAttempted + bAttempted == 3) {
        output2.setText("The bat turned into a statue...");
        board[bPosX][bPosY] = "S  ";
        success = 1;
        break;
      }
      output2.setText(out);
      if (testOne + testTwo + testThree > 3 - tAttempted + jAttempted + bAttempted || testOne + testTwo + testThree < 1 || testOne + testTwo + testThree > counter - 1) {
        output2.setText("Invalid response");
      }else if (vars.get(testOne + testTwo + testThree - 1).equals("t")) {
        int seed = (int)(Math.random() * 101);
        if (seed > 50) {
          output2.setText("Success! The bat was tamed and will now follow you!");
          cTamed = 1;
          board[bPosX][bPosY] = "   ";
          success = 1;
        }else {
          output2.setText("Failed!"); 
          vars.remove(testOne + testTwo + testThree - 1);
          tAttempted = 1;
        }
      }else if (vars.get(testOne + testTwo + testThree - 1).equals("j")) {
        int seed2 = (int)(Math.random() * 101);
        if (seed2 > 50) {
          output2.setText("Success! You jumped over the bat and avoided it, but it is still there!");
          success = 1;
        }else {
          output2.setText("Failed!");
          vars.remove(testOne + testTwo + testThree - 1);
          jAttempted = 1;
        }
      }else if (vars.get(testOne + testTwo + testThree - 1).equals("b")) {
        int seed3 = (int)(Math.random() * 101);
        if (seed3 > 50) {
          output2.setText("Success! You baited the bat away!");
          success = 1;
          board[bPosX][bPosY] = "   ";
        }else {
          output2.setText("Failed!");
          vars.remove(testOne + testTwo + testThree - 1);
          bAttempted = 1;
        }
      }
      counter = 1;
    }
    boardUpdate();
  }
  public static void hitStar(int sPosX, int sPosY) {
    output2.setText("You consumed a star and gained 10 health!");
    board[sPosX][sPosY] = "   ";
    boardUpdate();
  }
  public static void main(String[] args) {
    CreateReadOnlyJTextField.main(set);
    try {
      FileInputStream saveFile = new FileInputStream(saveName);
      ObjectInputStream save = new ObjectInputStream(saveFile);
      posX = (int) save.readObject();
      posY = (int) save.readObject();
      posXPast = (int) save.readObject();
      posYPast = (int) save.readObject();
      chance = (int) save.readObject();
      board = (String[][]) save.readObject();
      row1 = row2 = row3 = row4 = row5 = row6 = row7 = row8 = row9 = row10 = row11 = "";
      for (int r1 = 0; r1 < 11; r1++) {
        row1 += board[0][r1];
        row2 += board[1][r1];
        row3 += board[2][r1];
        row4 += board[3][r1];
        row5 += board[4][r1];
        row6 += board[5][r1];
        row7 += board[6][r1];
        row8 += board[7][r1];
        row9 += board[8][r1];
        row10 += board[9][r1];
        row11 += board[10][r1];
      }
      save.close();
      mainRecall();
    } catch (Exception exc) {
      try {
        FileOutputStream saveFile = new FileOutputStream(saveName);
        ObjectOutputStream save = new ObjectOutputStream(saveFile);
        save.writeObject(posX);
        save.writeObject(posY);
        save.writeObject(posXPast);
        save.writeObject(posYPast);
        save.writeObject(chance);
        save.writeObject(board);
        save.close();
        boardInit();
        mainRecall();
      } catch (Exception exc1) {
        exc.printStackTrace();
      }
    }
  }
}
class CreateReadOnlyJTextField extends JFrame {
  private static final long serialVersionUID = 1L;
  public CreateReadOnlyJTextField() {
    this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), 1));
    Main.row1L.setText("X    X    X    X    X    X    X    X    X    X    X");
    Main.row2L.setText("X                                                 X");
    Main.row3L.setText("X                                                 X");
    Main.row4L.setText("X                                                 X");
    Main.row5L.setText("X                                                 X");
    Main.row6L.setText("X                                                 X");
    Main.row7L.setText("X                                                 X");
    Main.row8L.setText("X                                                 X");
    Main.row9L.setText("X                                                 X");
    Main.row10L.setText("X                        @                        X");
    Main.row11L.setText("X    X    X    X    X    X    X    X    X    X    X");
    Main.output.setText("Which direction would you like to travel, or would you rather SAVE your path");
    Main.output2.setText("");
    Main.row1L.setEditable(false);
    Main.row2L.setEditable(false);
    Main.row3L.setEditable(false);
    Main.row4L.setEditable(false);
    Main.row5L.setEditable(false);
    Main.row6L.setEditable(false);
    Main.row7L.setEditable(false);
    Main.row8L.setEditable(false);
    Main.row9L.setEditable(false);
    Main.row10L.setEditable(false);
    Main.row11L.setEditable(false);
    Main.output.setEditable(false);
    Main.output2.setEditable(false);
    JTextField textField = new JTextField();
    textField.addKeyListener(new MKeyListener());
    Main.row1L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row2L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row3L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row4L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row5L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row6L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row7L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row8L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row9L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row10L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row11L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.output.setFont(new Font("Courier", Font.PLAIN, 16));
    Main.output2.setFont(new Font("Courier", Font.PLAIN, 16));
    add(textField);
    add(Main.row1L);
    add(Main.row2L);
    add(Main.row3L);
    add(Main.row4L);
    add(Main.row5L);
    add(Main.row6L);
    add(Main.row7L);
    add(Main.row8L);
    add(Main.row9L);
    add(Main.row10L);
    add(Main.row11L);
    add(Main.output);
    add(Main.output2);
  }
  private static void createAndShowGUI() {
    JFrame frame = new CreateReadOnlyJTextField();
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI(); 
      }
    });
  }
}

class MKeyListener extends KeyAdapter {
  @Override
  public void keyPressed(KeyEvent e) {
    if (e.getKeyText(e.getKeyCode()).equals("Up") || e.getKeyText(e.getKeyCode()).equals("W")) {
      Main.upTest = true;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("Down") || e.getKeyText(e.getKeyCode()).equals("S")) {
      Main.downTest = true;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("Left") || e.getKeyText(e.getKeyCode()).equals("A")) {
      Main.leftTest = true;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("Right") || e.getKeyText(e.getKeyCode()).equals("D")) {
      Main.rightTest = true;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("1")) {
      Main.testOne = 1;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("2")) {
      Main.testTwo = 2;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("3")) {
      Main.testThree = 3;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("Enter")) {
      Main.enterTest = true;
      Main.mainRecall();
    }
  }
}

Please help me...

It looks like you're doing a LOT of work on the UI thread. You will probably have a more responsive application if you run mainRecall() inside another thread. Games usually have a UI thread that draws things on-screen and one or more background threads that do the computationally-intensive work for just this reason. Often there's a concept of a perpetually-running loop in the background thread that just checks (and adjusts) the position of each game element, checks to see if one object has hit another, etc instead of checking performing those actions when a given key is pressed.

A pseudo-code example of the background thread is:

while(true) {
  for each nonPlayerObject
    processNextMove()
    checkForCollision()
  end for
  for each playerObject
    processNextMove()
    checkForCollision()
    recalculateScore()
  end for
  sleep(5)
}

On the UI thread you might also listen for user input and pass it to the background thread, eg so the player's movements can be redrawn immediately.

In Java you can create and run a new thread with

new Thread(new Runnable() {
        public void run() {
            while(true) {
               System.out.println("I am running in a background thread");
               try { Thread.sleep(100); } catch (InterruptedException e) {}
            }
        }
}).start();

For more information on creating and running threads, see http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html#anonymous-implementation-of-runnable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM