Eugenio Olivieri
Eugenio Olivieri

Reputation: 21

Save Player Stats C#

Im finally finish my Rpg Game in C# Visual Studio 2013. It remains one last thing to do : save my player stats and inventary (that is inside the player class itself) to a file to reload it later and continue playing from that exp and level. Im a beginner and really dont know how and what/where serialize things. My game rpg text game is linked just on player stats and item inside the inventory of my player so i need to save just this things. Here comes the problem. Im gonna write a short version of my code to let you understand how my rpg is organized and to let you help me with the code i have to insert for saving things.

Just two simple classes for now. I have my solution "THE_GAME" with its form "Game" in my project directory , then i've added a new class library named "Engine" and i've added "Engine" ad reference for my project The_Game,so my Game uses code in Engine project. In Engine i have a lot of classes...but for now and in a short code i wanna talk about the "Player" and "Magicians" classes . This class in Engine is "short version" :

MAGICIANS CLASS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Engine
{
    public class Magicians
    {

        public int Hp { get; set; }
        public int Defense { get; set; }

public Magicians(int hp, int defense){
            Hp = hp;
            Defense = defense;

PLAYER CLASS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Engine
{
    public class Player : Magicians
    {


        public int ExpPoints { get; set; }
        public int hp {get;set;}
        public List<InventoryItem> Invetory { get; set; }
        public int Level
        {
            get { return ((ExpPoints / 1000) + 1); }
        }

public Player(int exppoints, int hp,int level) : base(hp, defense){

ExpPoints = expoints;
Inventory = new List<InventoryItem>();
}

Ok now this is my Game class and form where i put things that my game does (outside Engine).

    using Engine;

    namespace Magicians_game
    {
        public partial class MagiciansGame : Form
        {



            private Player _player;

    public MagiciansGame()
            {
                InitializeComponent();

    _player = new Player(0,100,1);
    _player.Inventory.Add(new InventoryItem(......);

                lblHp.Text = _player.Hp.toString();
                lblExp.Text = _player.ExpPoints.ToString();

Well...now follow al the code of combat functions etc etc.... Ok my game works perferctly. What i have to do to save to a file, during the game progress, my player stats (hp exp item inventory) ? Where i have to put the [Serializable] tag? In Magicians or in all classes? Ok but then? what is the code and where i have to put that code to save to a file?

Upvotes: 0

Views: 2068

Answers (2)

Quality Catalyst
Quality Catalyst

Reputation: 6795

Check this article from Microsoft Support: "How to serialize an object to XML by using Visual C#" http://support.microsoft.com/kb/815813 - here is explained how to serialize your objects into XML - it's one form of serialization. There are other options of course.

Once you have a serialized object you can save the result into a file.

Example:

Player myPlayer = new Player();
using (StreamWriter writer = File.CreateText("player.xml"))
{
    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(myPlayer.GetType());
    x.Serialize(writer, myPlayer);
}

Upvotes: 4

Joey Quinto
Joey Quinto

Reputation: 367

Quality Catalyst's answer is great; here is a supplementary class that will be useful in re using this method for any class you want to serialize and/or derserialize :)

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

//USAGE:

//To Serialize a Serializable class:
    //string serialized = XMLManager.Save<ClassToSerialize>(classInstance);

//To Deserialize a Serializable class from a serialized string:
    //ClassToSerialize classInstance = XMLManager.Load<ClassToSerialize>(serializedString);

public static class XMLManager
{
    public static string Save<T>(T data)
    {
        XmlSerializer xml = new XmlSerializer(typeof(T));
        StringWriter write = new StringWriter();
        xml.Serialize(write, data);

        return write.ToString();
    }

    public static T Load<T>(string xmlString) where T : class
    {
        try
        {
            StringReader outStream = new StringReader(xmlString);
            XmlSerializer xml = new XmlSerializer(typeof(T));
            return (T)xml.Deserialize(outStream);
        }
        catch (Exception e)
        {
            //error here
            throw new Exception("XMLManager caught an Exception!", e);
        }
    }
}

Upvotes: 0

Related Questions