Reputation: 1576
I am making some sort of turn-based battle system in a JFrame where the player clicks a button when it's his turn. The problem is: how can the program wait for a mouse click on the button? It goes like this:
while it is the player's turn {
wait for mouse input
if input == attack (for example)
-> attack
else if input == item
-> use item
and so on
Upvotes: 0
Views: 2518
Reputation: 81684
You don't wait for a click; you let Swing do that for you. Instead, you put whatever you want to do into an ActionListener
and attach it to the button, so it gets executed when the button is clicked.
As far as the turns go, you just need a member variable someplace that keeps track of whose turn it is; the button handler then has to look at that variable to know what to do.
One good way to structure things, by the way, might be to have a Player
class, and a Game
class, and a member in Game
called currentPlayer
. Then the ActionListener
(which keeps the Game
object as a member variable of its own) could look at currentPlayer
in the Game
and simply invoke makeMove()
on the appropriate Player
object.
Upvotes: 3