AdSense

Monday, 10 June 2013

Minecraft Server - Find out the players' positions with C#

(Deutsche Version) I am running a small (private) Minecraft server. After some time it became necessary to have a map where you can see every player.


The players' positions are saved on the server in the directory /world/players/<name>.dat and will be refreshed every 45 seconds. This is not very much but ok for a coarse map.


To read the .dat files, I use the library "LibNbt", https://github.com/aphistic/libnbt, because of the files being saved in binary format and not as plain text. After the download, simply extract everything and include the LibNbp projct into the own C# project and add a reference.

The code to read the position is the following:

DirectoryInfo d = new DirectoryInfo(@"world\players\");
var file = new NbtFile();
//A file in which the positions are saved
StreamWriter outFile = new StreamWriter("positions.dat");
string lines = "";
//run through all players
foreach (var file1 in d.GetFiles("*.dat"))
{
    //load player file
    file.LoadFile(d + file1.Name);
    NbtCompound root = file.RootTag;
    int i = 0;
    //run through all tags until the Pos tag is found
    foreach (NbtTag tag in root.Tags)
    {
        if (tag.Name.Equals("Pos"))
        {
            NbtList posList = ((NbtList)root[i]);
            //save as string
            lines += file1.Name.Substring(0,file1.Name.Length-4)

                                  + "\t"
                  + ((NbtDouble)posList[0]).Value
                                  + "\t"
                  + ((NbtDouble)posList[2]).Value
                                  + "\r\n";
        }
        i++;
    }

}
outFile.WriteLine(lines);
outFile.Close();

To show everything on a map, I used the program "AMIDST" for making a screenshot of my world (from -4096, -3072 to 4096, 3072). After that I calculate the players' positions in pixel and paint them on the map with another program which is only used for displaying.

No comments:

Post a Comment