At the moment I'm currently re-writing a text-based program to have a GUI. One of the problems I am experiencing is that I want the program to wait until a certain condition is met. This condition can be met through the user clicking the "Walk" button until the player.walked attribute = 5. When using a text-based interface this is quite simple, use a while loop and inside have an input function.
while (player.getWalked() < 5) {
//wait for user input via terminal through the scanner.
}
However when using a GUI and wanting to follow the approach of the Model-View Controller (i.e. keeping game mechanics and user interface stuff separate) it becomes rather difficult. After attempting to implement a GUI My program keeps freezing as the while loop is now empty. I will attempt to evidence this below but it is rather confusing. I apologise if this is unprofessional.
World Class:
public static void play(Player player) throws FileNotFoundException, IOException, ClassNotFoundException{ // play method is the centralised place for all in-game simulation and user interaction.
welcome(player);
while (player.getWalked() <5) {
}
GUI Class:
Button walk_button = new Button("Walk");
walk_button.setBounds(195, 395, 100,100);
add(walk_button);
walk_button.addActionListener((new ActionListener(){
public void actionPerformed(ActionEvent evt) {
try{
label1.setVisible(false);
label.setText(player.interaction("W"));
label.setBounds(200,50,400,100);
}
catch (FileNotFoundException e) {System.out.println(e.getMessage());} catch (IOException e) {System.out.println(e.getMessage());} catch (ClassNotFoundException e) {System.out.println(e.getMessage());}
}
}));
Player class consisting of the interaction
method:
public String interaction(String input) throws FileNotFoundException, IOException, ClassNotFoundException{
//String input = World.input("You have walked "+getWalked()+" miles so far.\nOnly "+(END_POINT - walked)+" miles until you reach the end of the town.\nPress 'w' to walk.\nPress 'c' to change weapon equipped.\nPress 's' to save and exit.");
if (input.equals("W")) {
return walk(World.dice(4,1));
}
If anyone can find a solution to this I would be much appreciated. The end goal is for the program to keep running (allow the player to keep pressing the "Walk" button) until the while loop is broken.
Thank you very much and apologies if this is rather long, confusing and unprofessional.