Search code examples
javaevent-driventext-based

Making a text based game that waits for a JButton event


I'm looking for a way to make a simple text based game, though I'm having problems doing it in Event Driven rather than a game loop.

The basic way that the game plays: Says what monster you are fighting. Attack. When it is defeated, you go to the next monster.

In a game loop that uses the next line of a Scanner, I can wait for the user to enter a valid option, then continue the code. However using events, I'm not sure how to set up the game. I need to somehow wait for the user to press a button to do an action, but I don't know where I should register the event listener, how I can make a loop with actions events, etc.

Sorry if this is kind of vague, it's more of a semantics problem than a syntax one, and I'm just learning Java. I essentially need the basic structure of an event driven game that reacts differently depending on what stage of the game you are in.


Solution

  • The key with the event program is that you don't use a "loop" at all. Instead you change "state".

    The simplest version of this "state machine" would be a linear ArrayList of String where your program holds an int variable that represents the current item in the ArrayList, and you increment the index on button press, and then present to the next String in the list to the user. The beauty of the system is that you can use it for much more complex logical journeys, an almost infinite variety, each one depending on the current state of the game and the selection(s) made by the user.

    For more complex games, you would not use a linear script but rather would create multiple classes with behaviors (methods) and state (variables), and have them all interact with each other. These will include your Monster classes, your Item classes, and your Location classes, as well as a Game class to control everything.