Skip to content

Instantly share code, notes, and snippets.

@copygirl
Created June 18, 2015 23:14
Show Gist options
  • Save copygirl/b32fccb39132c976906c to your computer and use it in GitHub Desktop.
Save copygirl/b32fccb39132c976906c to your computer and use it in GitHub Desktop.
// The NBT tags to copy from the player file to the backup.
static string[] tagsToCopy = { "XpLevel", "XpP", "Inventory", "EnderItems" };
===
var player = TagBase.Load("<player>.dat"); // Load the file
var backup = new TagCompound(); // Create an empty NBT tag
// Copy over the wanted tags from the file to the empty NBT tag
for (var tag in tagsToCopy)
// .Copy() or .Clone() would be a good idea here, but that's not in
// the library at the moment. Though it doesn't matter in this case.
backup[tag] = player[tag];
int experienceLevel = (int)player["XpLevel"];
float experienceProgress = (float)player["XpP"];
// Go over all the items in the inventory.
for (var item in (TagList)player["Inventory"]) {
var slot = (byte)item["Slot"];
var id = (string)item["id"];
var count = (byte)item["Count"];
var damage = (short)item["Damage"];
// Do something with the item..?
if (id == "minecraft:written_book") {
var author = (string)item["tag"]["author"];
var title = (string)item["tag"]["title"];
var pages = ((TagList)item["tag"]["pages"]).Select(x => (string)x).ToList(); // Requires using System.Linq
// Do something with books..?
}
}
===
// Turn the backup tag into a byte array to store in the database
using (var ms = new MemoryStream()) {
// Compressing might not be worth it, but you could use GZip compression of you wanted.
backup.Save(backup, null, NbtCompression.None);
var bytes = ms.ToArray();
// Do something with raw NBT data..?
}
===
// Grab the backup data from the database and restore everything
var bytes = ... // Get this from the database somehow
using (var ms = new MemoryStream(bytes)) {
var backup = TagBase.Load(ms, NbtCompression.None); // Wouldn't need to specify compression, will auto-detect it.
var player = TagBase.Load("<player>.dat"); // Just like it does with the player file.
// Copy backup data to player tag, overwriting them
for (var tag in tagsToCopy)
player[tag] = backup[tag];
// Save player data again
player.Save("<player>.dat", NbtCompression.GZip);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment