Reputation: 131
I wrote a simple little maze game for a terminal which repeatedly asks the user to do something (e.g. "In which direction would you like to go? [N/E/S/W]"). I have a navigate()
method running in a loop that fires off these questions, stores their answers and does something depending on the answer.
public enum Dir (N, E, S, W);
public void navigate() {
Dir nextDir = utils.askDirection("Which way do you want to go?");
// Do stuff with answer, like changing position of user in maze
}
Now, I've written a simple GUI for my game. I deliberately put all the references to the terminal in a ConsoleUtils
class which implements a Utils
interface (this has methods like askQuestion()
) - the idea being that I could create a GuiUtils
class and have my game either as a terminal game or as a GUI game.
The problem is that the navigate
method asks the user a question and then "waits" for the response, which the Utils
class gives it by using a Scanner
to read the newest line of input. However if I use Event Listeners for the new N/E/S/W buttons in my GUI, they fire off events regardless whether the navigate
method has asked for one or not.
--> Image of GUI
Is there any way I can combine this or do I need to write a new navigate
method for the GUI?
(To be honest, I'm also not entirely sure whether my GUI class should instantiate a game
class, in which case the logic for navigate
could end up in a GUI method anyway, or whether the game should have a GUI. I haven't written any code for the event listener either yet, since I'm not sure which class should be calling which. This is probably a separate question.)
Upvotes: 2
Views: 544
Reputation: 205865
Your text based game has a loop that repeatedly asks questions to gather user input. Swing provides this loop for you by continually executing Runnable
blocks of code that have been posted to the EventQueue
. For example, when the user presses a button labeled E, code is posted to the queue that invokes your ActionEvent
implementation to handle your game's interpretation of the move east
command.
For reference, a complete example of a very simple guessing game is examined here. In pseudocode, the corresponding text based game might look like this:
initialize
loop
prompt "Guess what color!"
get chosenColor
if chosenColor = actualColor
say "You win!"
reset game
else
say "Keep trying."
end loop
A more elaborate game cited there includes the original text-based source.
Upvotes: 5