Click here to Skip to main content
15,891,811 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SpaceShipTravel.Scoring
{
    class Score
    {
        public string Name;
        public int Value;
        public Score()
        {
        }
        public Score(string name, int value)
        {
            Name = name;
            Value = value;
        }
    }
}


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SpaceShipTravel.Scoring
{
    class ScoreList
    {
        List<score> scores = new List<score>();
        int maxScoredStored = 10;
        public ScoreList()
        {
        }
        public void AddScore(Score newScore)
        {
            scores.Add(newScore);
            scores.Add(new Score ("Maggi", 3000));
            scores.Add(new Score("Ingle", 3600));
            if (scores.Count <= maxScoredStored)
            {
                return;
            }
            else
            {
                scores.Sort((scoreOne, scoreTwo) => (scoreTwo.Value.CompareTo(scoreOne.Value)));
                scores.RemoveRange(maxScoredStored,
                scores.Count - maxScoredStored);
            }
        }
        public List<score> Scores
        {
            get
            {
                scores.Sort((scoreOne, scoreTwo) => (scoreTwo.Value.CompareTo(scoreOne.Value)));
                return scores;
            }
        }
    }
}


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Serialization;

namespace SpaceShipTravel.Scoring
{
    class Scores
    {
        private static SerializableDictionary<string, ScoreList> highScores = new SerializableDictionary<string, ScoreList>();
        public void AddScore(string type, string name, int value)
        {
            if (!highScores.ContainsKey(type))
            {
                highScores.Add(type, new ScoreList());
            }
            highScores[type].AddScore(new Score(name, value));
        }
        public List<Score> HighScores(string type)
        {
            return highScores[type].Scores;
        }
        public int CurrentHighScore(string type)
        {
            if (highScores.ContainsKey(type))
            {
                return highScores[type].Scores[0].Value;
            }
            return 0;
        }

        const string directory = "StorageDemo";
        public void Load()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!storage.FileExists("HighScores.dat"))
                {
                    return;
                }
                using (IsolatedStorageFileStream file = new IsolatedStorageFileStream(directory + "\\HighScores.dat", FileMode.Open, storage))
                {
                    using (XmlReader reader = XmlReader.Create(file))
                    {
                        highScores.ReadXml(reader);
                    }
                }
            }
        }
        public void Save()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                //create directory for data
                if (!storage.DirectoryExists(directory))
                    storage.CreateDirectory(directory);
                //delete any existing file
                if (storage.FileExists("HighScores.dat"))
                    storage.DeleteFile("HighScores.dat");
                using (IsolatedStorageFileStream file = new IsolatedStorageFileStream(directory + "\\HighScores.dat", FileMode.CreateNew, storage))
                {
                    using (XmlWriter writer = XmlWriter.Create(file))
                    {
                        highScores.WriteXml(writer);
                    }
                }

            }
        }
    }
}


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
namespace SpaceShipTravel.Scoring
{
    [XmlRoot("dictionary")]
    public class SerializableDictionary<dkey,> : Dictionary<dkey,>, IXmlSerializable
    {
        const string ItemTag = "item";
        const string KeyTag = "key";
        const string ValueTag = "value";
        public XmlSchema GetSchema()
        {
            return null;
        }
        public void ReadXml(XmlReader reader)
        {
            if (IsEmpty(reader))
            {
                return;
            }
            XmlSerializer keySerializer = new XmlSerializer(typeof(DKey));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(DValue));
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                if (reader.NodeType == XmlNodeType.None)
                {
                    return;
                }
                ReadItem(reader, keySerializer, valueSerializer);
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }

        private bool IsEmpty(XmlReader reader)
        {
            bool isEmpty = reader.IsEmptyElement;
            reader.Read();
            return isEmpty;
        }

        private void ReadItem(XmlReader reader, XmlSerializer keySerializer,XmlSerializer valueSerializer)
        {
            reader.ReadStartElement(ItemTag);
            this.Add(ReadKey(reader, keySerializer),
            ReadValue(reader, valueSerializer));
            reader.ReadEndElement();
        }

        private DKey ReadKey(XmlReader reader, XmlSerializer keySerializer)
        {
            reader.ReadStartElement(KeyTag);
            DKey key = (DKey)keySerializer.Deserialize(reader);
            reader.ReadEndElement();
            return key;
        }
        private DValue ReadValue(XmlReader reader, XmlSerializer valueSerializer)
        {
            reader.ReadStartElement(ValueTag);
            DValue value = (DValue)valueSerializer.Deserialize(reader);
            reader.ReadEndElement();
            return value;
        }
        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(DKey));
            XmlSerializer valueSerializer  = new XmlSerializer(typeof(DValue));
            foreach (DKey key in this.Keys)
            {
                WriteItem(writer, keySerializer, valueSerializer, key);
            }
        }
        private void WriteItem(XmlWriter writer, XmlSerializer keySerializer, XmlSerializer valueSerializer, DKey key)
        {
            writer.WriteStartElement(ItemTag);
            WriteKey(writer, keySerializer, key);
            WriteValue(writer, valueSerializer, key);
            writer.WriteEndElement();
        }
        private void WriteKey(XmlWriter writer, XmlSerializer keySerializer, DKey key)
        {
            writer.WriteStartElement(KeyTag);
            keySerializer.Serialize(writer, key);
            writer.WriteEndElement();
        }
        private void WriteValue(XmlWriter writer, XmlSerializer valueSerializer, DKey key)
        {
            writer.WriteStartElement(ValueTag);
            valueSerializer.Serialize(writer, this[key]);
            writer.WriteEndElement();
        }

    }
}


//Calling class Gameover for above classes
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
using SpaceShipTravel.Texts;
using SpaceShipTravel.Sprites;
using SpaceShipTravel.Scoring;

namespace SpaceShipTravel.Screens
{
    class GameOver:Screen
    {
        Background background;
        Text gameOverText;
        Button playAgainButton;
        Button exitGameButton;

        const string ActionPlayAgain = "PlayAgain";
        const string ActionExitGame = "ExitGame";

        SpriteFont scoreFont;
        Text scoreText;
        Text highScoreTitleText;

        public GameOver(Game game, SpriteBatch batch, ChangeScreen changeScreen)
            : base(game, batch, changeScreen, BackButtonScreenType.Other)
        {
        }
        protected override void SetupInputs()
        {
            input.AddTouchGestureInput(ActionPlayAgain, GestureType.Tap, playAgainButton.CollisionRectangle);
            input.AddTouchGestureInput(ActionExitGame,  GestureType.Tap, exitGameButton.CollisionRectangle);
        }
        protected override void LoadScreenContent(ContentManager content)
        {
            background = new Background(content);
            gameOverText = new Text(font," Game Over", new Vector2(100, 50), Color.MistyRose, Color.Beige, Text.Alignment.Horizontal,new Rectangle(0,0, ScreenWidth,0));
            playAgainButton = new Button(content, "Play Again" , new Vector2(30, 500), Color.MistyRose);
            exitGameButton = new Button(content, "Exit" , new Vector2(30, 650), Color.MistyRose);
            scoreFont = content.Load<SpriteFont>("Fonts/scoreFont");
            scoreText = new Text(scoreFont, "Total Coins: ", new Vector2(30, 0));
            highScoreTitleText = new Text(scoreFont,":::High Scores:::", new Vector2(33, 130), Color.White, Text.Alignment.Horizontal, new Rectangle(0, 0, ScreenWidth, 0));

        }
        public override void Activate()
        {
            highScores.Save();
        }
        protected override void UpdateScreen(GameTime gameTime, DisplayOrientation displayOrientation)
        {
            if (input.IsPressed(ActionPlayAgain))
                {
                soundEffects.Playsound("SoundEffects/Select");
                changeScreenDelegate(ScreenState.MainGame);
                }
                else if (input.IsPressed(ActionExitGame))
                {
                changeScreenDelegate(ScreenState.Exit);
                }
        }
        protected override void DrawScreen(SpriteBatch batch, DisplayOrientation displayOrientation)
        {
            background.Draw(batch);
            gameOverText.Draw(batch);
            playAgainButton.Draw(batch);
            exitGameButton.Draw(batch);

            highScoreTitleText.Draw(batch);
            scoreText.Position.Y = 150;
            int topScorePosition = 1;
            foreach (Score score in highScores.HighScores("Coins"))
            {
                scoreText.Position.Y += 30;
                string name = score.Name + "    " ;
                scoreText.ChangeText(topScorePosition.ToString("00")+ "  " + name.Substring(0, 15)+ " " + score.Value.ToString("000") + "coins");
                scoreText.Draw(batch);
                topScorePosition += 1;
            }
        }
    }
}
Posted
Updated 5-Jul-14 23:55pm
v2
Comments
Member 10778143 24-Jun-14 2:09am    
Please resolve my query as soon as possible... i'm stucked over it from weeks... and as soon as I change extension of "Highscores.dat" to "Highscores.xml" it shows first chance exception System.xml... not found in System.Windows.ni.dll
George Jonsson 6-Jul-14 6:01am    
Have you tried to set a breakpoint in this method?
protected override void LoadScreenContent(ContentManager content)

1 solution

Start by looking at your Load method:
C#
public void Load()
{
    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (!storage.FileExists("HighScores.dat"))
        {
            return;
        }
        using (IsolatedStorageFileStream file = new IsolatedStorageFileStream(directory + "\\HighScores.dat", FileMode.Open, storage))
        {
            using (XmlReader reader = XmlReader.Create(file))
            {
                highScores.ReadXml(reader);
            }
        }
    }
}
A quick check says that you look for the existance of a file in one folder, then try to open it from another:
C#
if (!storage.FileExists("HighScores.dat"))

C#
const string directory = "StorageDemo";
using (IsolatedStorageFileStream file = new IsolatedStorageFileStream(directory + "\\HighScores.dat", FileMode.Open, storage))
using (XmlReader reader = XmlReader.Create(file))

Which is probably causing your problem.

Instead of this, create a class level string holding the full path (not relative to the current folder as your code is) to the file and always use that - in the Load and Save methods.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900