0
\$\begingroup\$

I'm thinking about making a StateManager for my game. I want to know how to design it; that is, how to use a stack to push and pop states onto, and draw them to the screen.

For example, should each State be a JPanel? I want to make a Menu, preferably using JButtons if possible. I don't want to add them directly to the main panel because I don't want to have to constantly add and remove those buttons. Also, not all my states are going to be drawable, since I might have a state that contains a MouseListener to detect clicks.

Right now, I have an empty State class. My Menu class extends from that. My state stack is of the type State. Another design question: if in my Menu I click the "Play" button, should I just say something like StateManager.push(new PlayState()) from the Menu class?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

For example, should each State be a JPanel?

It's generally better to favor aggregation over inheritance. So your State class shouldn't be a JPanel (= inherit from it), but should probably contain a JPanel member for rendering its content.

That's because your states don't do rendering only, but also manage many other things. Better yet, if for some reason you need states without a JPanel this might mean less code changes.

If in my Menu I click the "Play" button, should I just say something like StateManager.push(new PlayState()) from the Menu class?

Sure! Just make sure your StateManager releases the reference to the Menu state when it's done switching to PlayState. Otherwise you'll get memory leaks.

\$\endgroup\$
2
  • \$\begingroup\$ Does every state have handle its own input, or is that done by the State Manager? For example, if I have HUD that is clickable, like "Pause," but my game involves clicking on tiles to move, how can I be sure that my State Manager will know to pause the game instead of move my player? \$\endgroup\$
    – helsont
    Aug 6, 2012 at 3:30
  • \$\begingroup\$ Well, as you've find out yourself, this is probably better to handle inputs directly in your state objects. If you've got overlapping states as you describe, enable input processing on the topmost state only. \$\endgroup\$ Aug 6, 2012 at 16:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .