Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
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? –  user1264811 Aug 6 '12 at 3:30
    
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. –  Laurent Couvidou Aug 6 '12 at 16:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.