Sunday, March 16, 2008

Basic Menu

Well, it's been busy lately, but I've got a solid start on the menu, so I thought I'd post what I have as a forcing function to make me clean up my code. You can grab the source here. To use the menu system, you need to an instance of the GameMenu in you code. You can declare this in you game class (don't forget to put "using GameMenu;" at the top of your code"):

Menu mainMenu;


Then, in LoadContent(), initialize the menu, it's choices, and any handlers you want to catch.

mainMenu = new GameMenu.Menu(this);

mainMenu.AddChoice("Show Sprite");

mainMenu.AddChoice("Return");

mainMenu.ChoiceExecuted += new Menu.ChoiceExecutedHandler(ChoiceExecuted);



Of course, ChoiceExecuted should be defined somewhere. I'll get to that at the end. In your Update() method, call the game menu's update function:



mainMenu.Update(gameTime);


And in the Draw() method, call the menu's draw function:

mainMenu.Draw(gameTime);


If the menu isn't visible, those functions will do nothing. To show the menu, you set the visible property to true. I do this in the Update method when the user pressed escape:

if (keyboardState.IsKeyDown(Keys.Escape) && !prevKeyBoardState.IsKeyDown(Keys.Escape))

{

mainMenu.visible = !mainMenu.visible;

}


And finally, when a menu choice is executed, you handle it as follows:

public void ChoiceExecuted(object source, Menu.MenuEvent e)

{

if (e.choiceString == "Show Sprite")

{

mainMenu.visible = false;

}

else if (e.choiceString == "Return")

{

mainMenu.visible = false;

}

}


All I'm doing in the sample code is hiding the menu, but you can do anything in there. There are also choiceSelected and choiceDeselected events, and they get fired in the current code.


My next update to this code should have the ability to navigate through menu pages, and the ability to give the user some left/right choices as far as options go (a "Sound On Off" menu choice, for example).


No comments: