High Score System

Some question about it

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 9914 Views - Last Post: 05 July 2010 - 04:02 PM

#1 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,276
  • Joined: 01-June 09

High Score System

Posted 04 July 2010 - 10:59 AM

Well I want to add a high score system to my game. Since at the time being I really have no plan of putting this game on the 360, I'm just trying to make a high scores list local to the computer on which this game is being played. I've decided to take the text file approach. When you finish a game, the name of the player and score will be written to a text file, and then that text file will be read to the highscore page every time it's opened.

Right now, I'm able to read the score to a text file every time the game is won. No problem there. Now I'm just having a bit of trouble asking the player to input a name.

I'm going to have a screen pop up asking the player to enter his/her name. As the player presses a key, say a 'z' for example I want that drawn to the screen.

After researching a bit, I came up with what I figured would be an appropriate algorithm, but I'm having a little bit of trouble. Here's the code:
 public override void Draw(GameTime gameTime)
        {
            spriteBatch.Draw(image, imageRectangle, Color.White);

            KeyboardState keyboardState = Keyboard.GetState();
            string playerName = "";
            Keys[] pressedKeys = keyboardState.GetPressedKeys();
            int i = 0;
            
            while (!keyboardState.IsKeyDown(Keys.Enter))
            {
                playerName += pressedKeys[i].ToString();
                i++;

                spriteBatch.DrawString(spriteFont, playerName, new Vector2(Game.window.ClientBounds.Width / 2,
                                                            Game.window.ClientBounds.Height / 2), Color.White);
            }
           
            base.Draw(gameTime);
        }



The run time error is occurring here:
playerName += pressedKeys[i].ToString();



At the point where this screen is suppose to pop up, the game freezes. I get an error that says: IndexOutOfRangeException was unhandled. Index was outside the bounds of the array.

I suppose I can see why this is happening, but not sure how to fix it. I'm guessing the problem is in my logic. I'm not exactly sure how to get the input from the user and print it out one at a time.

Help would be greatly appreciated!

Thanks!

This post has been edited by eZACKe: 04 July 2010 - 11:08 AM


Is This A Good Question/Topic? 0
  • +

Replies To: High Score System

#2 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 929
  • View blog
  • Posts: 6,316
  • Joined: 18-October 08

Re: High Score System

Posted 04 July 2010 - 11:08 AM

What I would do is have a static class that handles input, shameless plug but you could use something similar to my Xin class. In that class have an event that is fired for each single keypress. In the screen where you are reading the keyboard input you just respond to the events and add the keys that you are interested in.

Even with out going that route, this is a method that will cycle through all pressed keys. You may be able to use the code from this method to do what you want, or modify it.

        private bool CheckPressedKeys()
        {
            KeypressEventArgs e;
            bool keyPressed = false;

            foreach (Keys key in lastKeyboardState.GetPressedKeys())
            {
                if (keyboardState.IsKeyUp(key))
                {
                    keyPressed = true;
                    e = new KeypressEventArgs(key);
                    if (Xin.KeyPress != null)
                    {
                        KeyPress(this, e);
                    }
                }
            }
            return keyPressed;
        }


Was This Post Helpful? 1
  • +
  • -

#3 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,276
  • Joined: 01-June 09

Re: High Score System

Posted 04 July 2010 - 11:26 AM

I touched up my draw method a little bit to try to do in your CheckPressedKeys() method above.

      public override void Draw(GameTime gameTime)
        {
            spriteBatch.Draw(image, imageRectangle, Color.White);

            keyboardState = Keyboard.GetState();
            
            
            while (!keyboardState.IsKeyDown(Keys.Enter))
            {
                //KeyboardState keyboardState = Keyboard.GetState();

                foreach (Keys key in keyboardState.GetPressedKeys())
                {
                    
                    
                    playerName += key.ToString();
                    

                    spriteBatch.DrawString(spriteFont, playerName, new Vector2(Game.window.ClientBounds.Width / 2,
                                                            Game.window.ClientBounds.Height / 2), Color.White);
                }
                

                
            }
            


            spriteBatch.DrawString(spriteFont, playerName, new Vector2(Game.window.ClientBounds.Width / 2,
                                                           Game.window.ClientBounds.Height / 2), Color.White);
             
           
            base.Draw(gameTime);

            oldKeyBoardState = keyboardState;

        }


       




Now it's not throwing any errors, but the game still freezes when the screen is suppose to show up (if I take out this logic and just show the screen then the screen does how up as expected).

The logic here is:
Until the user presses enter, for each key in the array Keys, once that key is up it will be converted to a string and then added on to an already existing string. Then that string will be drawn.

This post has been edited by eZACKe: 04 July 2010 - 12:53 PM

Was This Post Helpful? 0
  • +
  • -

#4 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,276
  • Joined: 01-June 09

Re: High Score System

Posted 04 July 2010 - 06:41 PM

Well thanks to SixOfEleven I was able to solve that problem. Thanks a lot!

Now I'm able to send the score of the game and the players name to a text file. The text file looks like this:


name, 3500
name, 3600
name, 2200
name, 3400
name, 3600
name, 3200
name, 3300
name, 3400
name, 3500
name, 3800
name, 3400
name, 3600
name, 2900
name, 3700
name, 3500
zack hine,3600
,3500
testertwo,3400
justin hine,3400
justin hine,3400
zacccck,3800
,3200
,3300
,3200
,3700
,3700
,3700
,3300
ffffffffff,3800
,3300
thisiscooo,3500
whfakaltll,3500
justin,3700
,3600
,3300
,3500
,3400
no,3200
ezacke,3300
ezacke,3700
,3300




Now I'm attempting to read that information onto a screen. Not sorted or anything yet, just trying to get it on the screen looking exactly as it does in that text file.

So I am trying this:

 private void DrawText()
        {
            int i = 0;

            foreach (String score in theScores)
            {
                spriteBatch.DrawString(spriteFont, score, new Vector2(Game.window.ClientBounds.Width / 2,
                                        Game.window.ClientBounds.Height / 4 + (10 * i)), Color.Yellow);
                i++;
            }

        }


        public void ReadHighScores()
        {
            string filePath = "highscores.txt";
            string line;
            
        
            if (File.Exists(filePath))
            {
                StreamReader file = null;

                try
                {
                    file = new StreamReader(filePath);
                    while ((line = file.ReadLine()) != null)
                    {
                        theScores.Add(line);
                    }
                }
                finally
                {
                    if (file != null)
                    {
                        file.Close();
                    }
                }
            }
        }



I'm attempting to add every line into an ArrayList and then draw each element in the array list a little bit underneath each other. When I enter the HighScoreScreen nothing is shown on the screen.

Perhaps my filePath is incorrect? When I create the file I just do this:
 FileStream file = new FileStream("highscores.txt", FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write);



And somehow it ends up in here: 'C:\Users\Zack\Documents\Visual Studio 2008\Projects\fullGame1\fullGame1\bin\x86\Debug"

So am I correct in just calling the filePath "highscores.txt"?


What is going wrong? Thank you!

EDIT: This is solved. Careless mistake on my part. Forgot to even call the ReadHighScores method. After calling it in LoadContent(), everything works as planned.

This post has been edited by eZACKe: 04 July 2010 - 07:06 PM

Was This Post Helpful? 0
  • +
  • -

#5 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 929
  • View blog
  • Posts: 6,316
  • Joined: 18-October 08

Re: High Score System

Posted 04 July 2010 - 07:17 PM

Your game is, by default, run in the debug folder. With out adding a path before the file name the file will be written into the folder that your application starts in. I think part of your problem is the ToString for the ArrayList. Not 100% sure of that though.

I would consider reading each line as a string, split it on the comma to get the two parts. Have a class that has the two parts as a string. Pass them as parameters to the constructor. Override the ToString method to format them the way you would like. I would also consider something like the following for reading in the text file.

       public void ReadHighScores()
       {
           string filePath = "highscores.txt";
           string line;
           
            try
            {
                string line;
                file = new StreamReader(filePath);
                while ((line = file.ReadLine()) != null)
                {
                    string[] parts = line.Split(',');
                    theScores.Add(new HighScore(parts[0], parts[1]);
                }
            }
            catch (FileNotFoundException ex)
            {
                IntializeHighScores();
                WriteHighScores();
            }
            catch (Exception ex)
            {
                // Handle unexpected exception
            }
            finally
            {
                // Close the file
            }
       }



*edit*
you fixed this before I finished my reply.
Was This Post Helpful? 1
  • +
  • -

#6 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,276
  • Joined: 01-June 09

Re: High Score System

Posted 04 July 2010 - 07:26 PM

Thank you for that information though! I'm most likely going to be using your advice here in the near future for actually showing the high scores list like I want to.

Again, thanks a lot!
Was This Post Helpful? 0
  • +
  • -

#7 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,276
  • Joined: 01-June 09

Re: High Score System

Posted 04 July 2010 - 08:03 PM

Actually I am having a bit of a problem with this. It doesn't update the high scores unless I close out of the game.

Any guesses as to why?

Is it because I'm calling the method in LoadContent()? I don't think this should be the problem though because isn't LoadContent() going to be called every time I enter this screen? I can't call it in Update() cause then it will draw the strings every time Update is called, which obviously would be problematic.

This post has been edited by eZACKe: 04 July 2010 - 08:06 PM

Was This Post Helpful? 0
  • +
  • -

#8 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 929
  • View blog
  • Posts: 6,316
  • Joined: 18-October 08

Re: High Score System

Posted 05 July 2010 - 06:08 AM

You could call the read method from the show method of the high score screen or call it just before you switch to the high score screen. The LoadContent method of the Game1 class is only called once when the game starts. Same is true for any of the game components.
Was This Post Helpful? 0
  • +
  • -

#9 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,276
  • Joined: 01-June 09

Re: High Score System

Posted 05 July 2010 - 11:04 AM

I'm curious. If someone else was to play this game on their computer, what would the file creation thing do? Like, where would the file "highscores.txt" be created, and would everything still work the way I have it now?

Thanks!

EDIT: Well I just ran the game via the .exe instead of just through the debugger, and when I typed in the playerName(and it's suppose to create a file called highscores.txt), it killed it.

So I'm assuming that answers my question as to what it would do on someone else's computer too. But why?

This post has been edited by eZACKe: 05 July 2010 - 11:10 AM

Was This Post Helpful? 0
  • +
  • -

#10 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 929
  • View blog
  • Posts: 6,316
  • Joined: 18-October 08

Re: High Score System

Posted 05 July 2010 - 01:45 PM

You would want to use an installer for your game. You will have to set up write permission on that directory. I found that out recently when I entered a game into a competition. I ran the installer and when I tried to write out a preferences file the game crashed. If you use the installer that comes with Visual Studio you are ok. I used INNO Setup, which is a free installer, for my most recent games. It works great but requires you to do a little work. If you are interested in it I can share the script I created for installing XNA games.
Was This Post Helpful? 0
  • +
  • -

#11 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,276
  • Joined: 01-June 09

Re: High Score System

Posted 05 July 2010 - 01:47 PM

Ooh ok, that sounds great!
Was This Post Helpful? 0
  • +
  • -

#12 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 929
  • View blog
  • Posts: 6,316
  • Joined: 18-October 08

Re: High Score System

Posted 05 July 2010 - 01:51 PM

Will write up a quick tutorial for it. Shouldn't take too long.
Was This Post Helpful? 0
  • +
  • -

#13 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,276
  • Joined: 01-June 09

Re: High Score System

Posted 05 July 2010 - 02:11 PM

Sounds good, thank you very much!
Was This Post Helpful? 0
  • +
  • -

#14 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: High Score System

Posted 05 July 2010 - 03:16 PM

If you don't want to mess around with permissions (can be a pain on Vista), you can save the file to a location that you are almost always guaranteed to have permission to write to. For example, I usually create a directory in the current user's application data folder to store all my information (for example, "C:\Program Data\My Game\").

XNA also provides the Storage namespace. You shouldn't run into any permission issues using those classes. Here's a link.

@SixOfEleven: I would be interested in reading that tutorial as well. I usually use the installer project from VS, but I've been planning on looking into other options for a while. :)
Was This Post Helpful? 1
  • +
  • -

#15 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 929
  • View blog
  • Posts: 6,316
  • Joined: 18-October 08

Re: High Score System

Posted 05 July 2010 - 03:52 PM

I added the tutorial on using INNO Setup for installing XNA games here. I will mention, you can't install games that require LIVE classes, like a System Link game or Windows LIVE. I believe you need to get a license for Windows LIVE for that.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2