I've created a rectangle, that has its own class. In the class I have a delegate created, that closes the game.
Creating the delegate:
public event EventHandler ExitRequested = delegate { };
In the update method I tell when to execute it:
if (mouseState.LeftButton == ButtonState.Pressed)
{
ExitRequested(this, EventArgs.Empty);
}
In my main class I execute the delegate like this (the exitGame is a rectangle):
exitGame.ExitRequested += exitGame_ExitRequested;
What I'm wondering about is there a way how to remove all items from the screen? Lets say it's for a "new game" functionality. I tried to create this functionality the same way I created the exit functionality but I can't figure out how to remove the items...
As far as I understand, you are trying to remove all game entities / objects in order to start a new game. Usually this is achieved by storing entities in a collection, and then simply removing all collection entries when a 'new game' is needed. As for entities which are not generic, such as the player, usually you just reset every member that needs to be reset; position, points etc.
Say you have a class to hold information about entities, such as enemies:
And you then store all entities in a collection:
You update and draw each entity by looping through the collection:
Then when you want to start a new game, and effectively remove all entities, you can simply remove all entries in the Entities list. (For example using
List.Clear()
, there are many ways)Keep in mind this is an example which has not been tested, so to say. This is can be optimized, and is more to give you an idea of why collections are useful for organizing game objects / entities.