Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use and parse a text file in C# to initialize a component based game model

Tags:

c#

.net

parsing

I have a text file that should initialize my objects, which are built around a component based model, it is my first time trying to use a data driven approach and i'm not sure if i am heading in the right direction here.

The file i have currently in mind looks like this

EliteGoblin.txt

@Goblin.txt


[general]
hp += 20
strength = 12
description = "A big menacing goblin"
tacticModifier +=  1.3

[skills]
fireball

Where the @ symbol says which other files to parse at at that point The names in [] correspond with component classes in the code And below them is how to configure them

For example the hp += 20 would increase the value taken from goblin.txt and increase it by 20 etc.

My question is how i should go about parsing this file, is there some sort of parser built in C#?

Could i change the format of my document to match already defined format that already has support in .net?

How do i go about understanding what type is each value? int/float/string

Does this seem a viable solution at all?

Thanks in advance, Xtapodi.

like image 646
Xtapodi Avatar asked Dec 07 '22 02:12

Xtapodi


1 Answers

Drop the flat file and pick up XML. Definately look into XML Serialization. You can simply create all of your objects in C# as classes, serialize them into XML, and reload them into your application without having to worry about parsing a flat file out. Because your objects will act as the schema for your XML, you won't have to worry about casting objects and writing a huge parsing routine, .NET will handle it for you. You will save many moons of headache.

For instance, you could rewrite your class to look like this:

public class Monster
{
     public GeneralInfo General {get; set;}
     public SkillsInfo  Skills {get; set;}
}
public class GeneralInfo
{
  public int Hp {get; set;}
  public string Description {get; set;}
  public double TacticModifier {get; set;}
}
public class SkillsInfo
{
  public string[] SkillTypes {get; set;}
}

...and your XML would get deserialized to something like...

<Monster>
   <General>
       <Hp>20</Hp>
       <Description>A big menacing goblin</Description>
       <TacticModifier>1.3</TacticModifier>
   </General>
   <SkillTypes>
        <SkillType>Fireball</SkillType>
        <SkillType>Water</SkillType>
   </SkillTypes>
</Monster>

..Some of my class names, hierarchy, etc. may be wrong, as I punched this in real quick, but you get the general gist of how serialization will work.

like image 198
George Johnston Avatar answered Apr 17 '23 05:04

George Johnston