So in my last post, I discussed getting a Menu Image to display on the screen. At this point, we must add some functionality to the program. First, consider the situation the game is in. When you take in user input to either start viewing the high score or being paying the game, you no longer care about anything that happens in the main menu, you only care about the things that occur in the option that the user chose. So in this way, we should keep all 3 of these states separate. In the past, I had always used simply an INT variable to keep track of the state, performance wise, it’s a good idea, however for maintenance and code legibility, I decided to create an ENUM to encapsulate the 3 states that I wanted my game to be in. The first state would be the main menu, second would be the game, and third would be the hi-score window.
One major advantage in using these states is the way the Update method is called. There is only one update method that constantly runs, but using states, we can put all 3 modes into one method, and then divide the method into 3 independent sections that run only when an the variable tracking the state passes each of the respective modes.
Moving to another state
Within the update method provided, each of the three modes will have a method that is called only when the mode is active. The method for the hi-score mode is the one I chose to start making first, for the obvious reason that it is infinitely simpler than the game mode. For storing a high score, I decided to record the high score in arrays containing the name and score.
As far as printing it on the screen goes, that was a more difficult task. In beginner programming classes, you were heavily dependent on Conesole.WriteLine(“”) to give output. In XNA, no such method exists. There is a similar function, albeit one that is far more complicated. You call it from SpriteBatch.DrawString();. To be able to use the Draw String method, you must first create a font object and load a font into it. It is done much the same way as one would load an image into a Texture2D object. Now that we have a hi-score in the game, we must find a way to track the high score even when the game is off. I did this the only way I knew how, by storing data in a CSV(Comma Separated Values) file. The high score update method would check for the existence of a CSV file that stores the current hi scores. If no such file exists, it would then proceed to create one and initialize all values as something standard. Reading and Writing external files is done using the StreamReader and StreamWriter classes.
And finally for the high score state, you have one last method that checks for the ESC button being pressed. When it detects this, it changes the mode variable back to main menu. And thus, the high score mode won’t run on the next cycle.
No comments:
Post a Comment