I'm making a Console Application using Visual Studio, the coding is being written in (C#). The program is going to be a basic Command Prompt game.
So, I'm trying to find a way to store information.. I'm fairly new to coding in general, so I don't know what type of file I will need to make. I just want a way to store things like names, and character levels, so essentially strings and integers.
Although, I don't want to use a ".txt" file or something like that. I'm really looking for something embed into the program.
Thanks for taking the time to read my question; I'm happy to answer any further questions you may have, so that I can achieve what I'm working toward.
An easy and straightforward way would be to create a serializable class that stores all relevant data. This class can than be easily written to and read from e.g. a Xml file.
Sample code:
[Serializable]
public class GameData
{
public int Highscore;
/* Plus any other data you want to store */
}
public class Game
{
private const string gameDataLocation = "C:\\GameData.xml";
private GameData gameData;
/* Your game methods */
private void StoreData()
{
XmlSerializer serializer = new XmlSerializer(typeof(GameData));
StreamWriter writer = new StreamWriter(gameDataLocation);
serializer.Serialize(writer, gameData);
writer.Close();
}
private void LoadData()
{
XmlSerializer serializer = new XmlSerializer(typeof(GameData));
FileStream fileStream = new FileStream(gameDataLocation, FileMode.Open);
gameData = (GameData)serializer.Deserialize(fileStream);
fileStream.Close();
}
}
Totally missed Florians answer but I post this anyway since you might learn a few things from it even though it's essentially the same answer.
[Serializable]
public class Player
{
public string Name { get; set; }
public int Level { get; set; }
public Weapon Weapon { get; set; }
}
[Serializable]
public class Weapon
{
public string Name { get; set; }
public int MaxDamage { get; set; }
public int Range { get; set; }
public WeaponClass Class { get; set; }
public enum WeaponClass { Sword, Club, Bow }
}
and then you can use these like this
var filename = @"c:\temp\player.xml";
var sword = new Weapon { Name = "Dáinsleif", MaxDamage = 42, Range = 1, Class = Weapon.WeaponClass.Sword };
var player = new Player { Name = "Fafhrd", Level = 19, Weapon = sword };
var ser = new XmlSerializer(typeof(Player));
var file = File.OpenWrite(filename);
ser.Serialize(file, player);
file.Close();
player = null;
file = File.OpenRead(filename);
player = (Player)ser.Deserialize(file);
file.Close();
The XML:
<?xml version="1.0"?>
<Player xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Fafhrd</Name>
<Level>19</Level>
<Weapon>
<Name>Dáinsleif</Name>
<MaxDamage>42</MaxDamage>
<Range>1</Range>
<Class>Sword</Class>
</Weapon>
</Player>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With