本文整理汇总了Python中pymclevel.nbt.load函数的典型用法代码示例。如果您正苦于以下问题:Python load函数的具体用法?Python load怎么用?Python load使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了load函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_migration_data
def load_migration_data():
print("Loading migration data...")
data = nbt.load(RAW_DATA_FILE)
fromItems = {}
for (key, val) in data.items():
fromItems[key] = val
return fromItems
示例2: loadFile
def loadFile(fName):
if not fName:
fName = mcplatform.askOpenFile(title=_("Select a NBT (.dat) file..."), suffixes=['dat',])
if fName:
if not os.path.isfile(fName):
alert("The selected object is not a file.\nCan't load it.")
return
dontSaveRootTag = False
nbtObject = load(fName)
if fName.endswith('.schematic'):
nbtObject = TAG_Compound(name='Data', value=nbtObject)
dontSaveRootTag = True
dataKeyName = 'Data'
elif nbtObject.get('Data', None):
dataKeyName = 'Data'
elif nbtObject.get('data', None):
dataKeyName = 'data'
else:
nbtObject.name = 'Data'
dataKeyName = 'Data'
dontSaveRootTag = True
nbtObject = TAG_Compound([nbtObject,])
# dontSaveRootTag = not fName.endswith('.schematic')
return nbtObject, dataKeyName, dontSaveRootTag, fName
return [None,] * 4
示例3: testErrors
def testErrors(self):
"""
attempt to name elements of a TAG_List
named list elements are not allowed by the NBT spec,
so we must discard any names when writing a list.
"""
level = self.testCreate()
level["Map"]["Spawn"][0].name = "Torg Potter"
data = level.save()
newlevel = nbt.load(buf=data)
n = newlevel["Map"]["Spawn"][0].name
if n:
print "Named list element failed: %s" % n
# attempt to delete non-existent TAG_Compound elements
# this generates a KeyError like a python dict does.
level = self.testCreate()
try:
del level["DEADBEEF"]
except KeyError:
pass
else:
assert False
示例4: testBigEndianIntHeightMap
def testBigEndianIntHeightMap(self):
""" Test modifying, saving, and loading the new TAG_Int_Array heightmap
added with the Anvil format.
"""
chunk = nbt.load("testfiles/AnvilChunk.dat")
hm = chunk["Level"]["HeightMap"]
hm.value[2] = 500
oldhm = numpy.array(hm.value)
filename = mktemp("ChangedChunk")
chunk.save(filename)
changedChunk = nbt.load(filename)
os.unlink(filename)
eq = (changedChunk["Level"]["HeightMap"].value == oldhm)
assert eq.all()
示例5: testSpeed
def testSpeed():
d = join("testfiles", "TileTicks_chunks")
files = [join(d, f) for f in os.listdir(d)]
startTime = time.time()
for f in files[:40]:
n = nbt.load(f)
duration = time.time() - startTime
assert duration < 1.0 # Will fail when not using _nbt.pyx
示例6: __init__
def __init__(self, mapstore, dir_paintings='paintings', mapcolor=11141120,
paintingcolor=14079638):
self.mapstore = os.path.join(mapstore, 'data')
self.mapcolor = mapcolor
self.paintingcolor = paintingcolor
# Load the idcounts.dat NBT if it exists, otherwise make
# a new one.
try:
self.idcounts = nbt.load(
os.path.join(
self.mapstore,
'idcounts.dat'))
except:
print 'No idcounts.dat file found. Creating a new one...'
self.idcounts = nbt.TAG_Compound()
# Load the mcdungeon map ID usage cache
if (os.path.isfile(os.path.join(self.mapstore, 'mcdungeon_maps'))):
try:
with open(os.path.join(self.mapstore, 'mcdungeon_maps'), 'rb') as FILE:
self.mapcache = cPickle.load(FILE)
except Exception as e:
print e
print "Failed to read the mcdungeon maps cache file."
print "The file tracking MCDungeon map usage may be corrupt."
print "You can try deleting or moving this file to recover:"
print os.path.join(self.mapstore, 'mcdungeon_maps')
sys.exit(1)
else:
print 'Mapstore cache not found. Creating new one...'
self.mapcache = {'used': {}, 'available': set([])}
# Generate map hash table
self.maphash = {}
for file in os.listdir(self.mapstore):
if (str(file.lower()).endswith(".dat") and
str(file.lower()).startswith("map_")):
# Gen hash and extract map ID
hash = hashlib.md5(
open(
os.path.join(
self.mapstore,
file),
'r').read()).digest()
self.maphash[hash] = int(file[4:-4])
# Store paintings path
if os.path.isdir(os.path.join(sys.path[0], dir_paintings)):
self.painting_path = os.path.join(sys.path[0], dir_paintings)
elif os.path.isdir(dir_paintings):
self.painting_path = dir_paintings
else:
sys.exit("Error: Could not find the paintings folder!")
示例7: testLoad
def testLoad():
"Load an indev level."
level = nbt.load("testfiles/hell.mclevel")
# The root tag must have a name, and so must any tag within a TAG_Compound
print level.name
# Use the [] operator to look up subtags of a TAG_Compound.
print level["Environment"]["SurroundingGroundHeight"].value
# Numeric, string, and bytearray types have a value that can be accessed and changed.
print level["Map"]["Blocks"].value
return level
示例8: loadFile
def loadFile(fName):
if not fName:
fName = mcplatform.askOpenFile(title=_("Select a NBT (.dat) file..."), suffixes=['dat', ])
if fName:
if not os.path.isfile(fName):
alert("The selected object is not a file.\nCan't load it.")
return
savePolicy = 0
data = open(fName).read()
if struct.Struct('<i').unpack(data[:4])[0] in (3, 4):
if struct.Struct('<i').unpack(data[4:8])[0] != len(data[8:]):
raise NBTFormatError()
with littleEndianNBT():
nbtObject = load(buf=data[8:])
savePolicy = 1
elif struct.Struct('<i').unpack(data[:4])[0] in (1, 2):
alert(_("Old PE level.dat, unsupported at the moment."))
else:
nbtObject = load(buf=data)
if fName.endswith('.schematic'):
nbtObject = TAG_Compound(name='Data', value=nbtObject)
savePolicy = -1
dataKeyName = 'Data'
elif nbtObject.get('Data', None):
dataKeyName = 'Data'
elif nbtObject.get('data', None):
dataKeyName = 'data'
else:
nbtObject.name = 'Data'
dataKeyName = 'Data'
if savePolicy == 0:
savePolicy = -1
nbtObject = TAG_Compound([nbtObject, ])
return nbtObject, dataKeyName, savePolicy, fName
return [None] * 4
示例9: load
def load(self):
'''
Loads the 'mcedit_waypoints.dat' file from the world directory if it exists. If it doesn't exist, it sets the 'Empty' waypoint
'''
if self.editor.level is None:
return
if not os.path.exists(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat")):
self.build()
else:
self.nbt_waypoints = nbt.load(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat"))
self.build()
if not (len(self.waypoints) > 0):
self.waypoints["Empty"] = [0,0,0,0,0,0]
if "LastPosition" in self.nbt_waypoints:
self.editor.gotoLastWaypoint(self.nbt_waypoints["LastPosition"])
del self.nbt_waypoints["LastPosition"]
示例10: load
def load(self):
'''
Loads the 'mcedit_waypoints.dat' file from the world directory if it exists. If it doesn't exist, it sets the 'Empty' waypoint
'''
if self.editor.level is None:
return
if not os.path.exists(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat")):
self.build()
else:
try:
self.nbt_waypoints = nbt.load(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat"))
except nbt.NBTFormatError:
shutil.move(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat"), os.path.join(self.worldDirectory, u"mcedit_waypoints_backup.dat"))
log.warning("Waypoint data file corrupted, ignoring...")
finally:
self.build()
if not (len(self.waypoints) > 0):
self.waypoints["Empty"] = [0,0,0,0,0,0]
if "LastPosition" in self.nbt_waypoints:
self.editor.gotoLastWaypoint(self.nbt_waypoints["LastPosition"])
del self.nbt_waypoints["LastPosition"]
示例11: __init__
def __init__(self, mapstore):
self.mapstore = os.path.join(mapstore, 'data')
# Load the idcounts.dat NBT if it exists, otherwise make
# a new one.
try:
self.idcounts = nbt.load(os.path.join(self.mapstore, 'idcounts.dat'))
except:
print 'No idcounts.dat file found. Creating a new one...'
self.idcounts = nbt.TAG_Compound()
# Load the mcdungeon map ID usage cache
if (os.path.isfile(os.path.join(self.mapstore, 'mcdungeon_maps'))):
try:
with open(os.path.join(self.mapstore, 'mcdungeon_maps'), 'rb') as FILE:
self.mapcache = cPickle.load(FILE)
except Exception as e:
print e
sys.exit('Failed to read the mcdungeon maps cache file.')
else:
print 'Mapstore cache not found. Creating new one...'
self.mapcache = {'used': {}, 'available': set([])}
# Generate map hash table
self.maphash = {}
for file in os.listdir(self.mapstore):
if (str(file.lower()).endswith(".dat") and
str(file.lower()).startswith("map_")):
#Gen hash and extract map ID
hash = hashlib.md5(open(os.path.join(self.mapstore,file), 'r').read()).digest()
self.maphash[hash] = int(file[4:-4])
# Store paintings path
if os.path.isdir(os.path.join(sys.path[0],'paintings')):
self.painting_path = os.path.join(sys.path[0],'paintings')
elif os.path.isdir('paintings'):
self.painting_path = 'paintings'
else:
sys.exit("Error: Could not find the paintings folder!")
示例12: __init__
def __init__(self, mapstore):
self.mapstore = os.path.join(mapstore, 'data')
# Load the idcounts.dat NBT if it exists, otherwise make
# a new one.
try:
self.idcounts = nbt.load(os.path.join(self.mapstore, 'idcounts.dat'))
except:
print 'No idcounts.dat file found. Creating a new one...'
self.idcounts = nbt.TAG_Compound()
self.idcounts['map'] = nbt.TAG_Short(-1)
# Load the mcdungeon map ID usage cache
if (os.path.isfile(os.path.join(self.mapstore, 'mcdungeon_maps'))):
try:
with open(os.path.join(self.mapstore, 'mcdungeon_maps'), 'rb') as FILE:
self.mapcache = cPickle.load(FILE)
except Exception as e:
print e
sys.exit('Failed to read the mcdungeon maps cache file.')
else:
print 'Mapstore cache not found. Creating new one...'
self.mapcache = {'used': {}, 'available': set([])}
示例13: on_confirm_overwrite
def on_confirm_overwrite(self, chooser, param=None):
"""
Our own custom overwrite-confirm dialog
"""
try:
# Try to load it as NBT, and then try to access an Inventory
# structure. If we succeed, then we're trying to save-as
# an existing Minecraft level.dat, so we should use our custom
# dialog to see if the user wants to overwrite fully, or just
# do the inventory stuff. Otherwise, just use the default
# dialog.
nbtdata = nbt.load(self.get_filename())
test = nbtdata['Data'].value['Player'].value['Inventory'].value
except Exception:
self.overwrite_all = True
return gtk.FILE_CHOOSER_CONFIRMATION_CONFIRM
dialog = OverwriteConfirmDialog(self, filename=self.get_filename())
result = dialog.run()
self.overwrite_all = dialog.is_overwrite_all()
dialog.destroy()
if result == gtk.RESPONSE_YES:
return gtk.FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME
else:
return gtk.FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN
示例14: LoadNBTFiles
def LoadNBTFiles(dirname='items'):
# Test which path to use. If the path can't be found
# just don't load any items.
if os.path.isdir(os.path.join(sys.path[0], dirname)):
item_path = os.path.join(sys.path[0], dirname)
elif os.path.isdir(dirname):
item_path = dirname
else:
print 'Could not find the NBT items folder!'
return
#Make a list of all the NBT files in the items directory
itemlist = []
for file in os.listdir(item_path):
if (file.endswith(".nbt")):
itemlist.append(file)
items_count = 0
for item in itemlist:
# SomeItem.nbt would be referenced in loot as file_some_item
name = 'file_'+item[:-4].lower()
full_path = os.path.join(item_path, item)
# Load the nbt file and do some basic validation
try:
item_nbt = nbt.load(full_path)
item_nbt['id'] # Throws an error if not set
except:
print item + " is an invalid item! Skipping."
continue # Skip to next item
# If the Count tag exists, use it as our maxstack
try:
stack = item_nbt['Count'].value
except:
stack = 1
_items[name] = ItemInfo(name, 0, maxstack=stack, file=full_path)
#print _items[name]
items_count += 1
print 'Loaded', items_count, 'items from NBT files.'
示例15: buildItemTag
def buildItemTag(self,i):
# If it's a binary NBT file, just load it
if i.file != '':
item_tag = nbt.load(i.file)
# Set the slot and count
if i.slot != None:
item_tag['Slot'] = nbt.TAG_Byte(i.slot)
item_tag['Count'] = nbt.TAG_Byte(i.count)
return item_tag
# Otherwise, we will build the compound
item_tag = nbt.TAG_Compound()
# Standard stuff
item_tag['id'] = nbt.TAG_Short(i.id)
item_tag['Damage'] = nbt.TAG_Short(i.damage)
# Enchantments
if len(i.enchantments) > 0:
item_tag['tag'] = nbt.TAG_Compound()
if (i.flag == 'ENCH_BOOK'):
item_tag['tag']['StoredEnchantments'] = nbt.TAG_List()
elist = item_tag['tag']['StoredEnchantments']
else:
item_tag['tag']['ench'] = nbt.TAG_List()
elist = item_tag['tag']['ench']
for e in i.enchantments:
e_tag = nbt.TAG_Compound()
e_tag['id'] = nbt.TAG_Short(e['id'])
e_tag['lvl'] = nbt.TAG_Short(e['lvl'])
elist.append(e_tag)
# Custom Potion Effects
if i.p_effect != '':
try:
item_tag['tag']
except:
item_tag['tag'] = nbt.TAG_Compound()
item_tag['tag']['CustomPotionEffects'] = nbt.TAG_List()
elist = item_tag['tag']['CustomPotionEffects']
for e in i.p_effect.split(','):
id, amp, dur = e.split('-')
e_tag = nbt.TAG_Compound()
e_tag['Id'] = nbt.TAG_Byte(id)
e_tag['Amplifier'] = nbt.TAG_Byte(amp)
e_tag['Duration'] = nbt.TAG_Int(dur)
# Flags for hiding potion particles
if i.flag == 'HIDE_PARTICLES' or i.flag == 'HIDE_ALL':
e_tag['ShowParticles'] = nbt.TAG_Byte(0)
elist.append(e_tag)
# Flag for hiding additional text
if i.flag == 'HIDE_EFFECTS' or i.flag == 'HIDE_ALL':
try:
item_tag['tag']
except:
item_tag['tag'] = nbt.TAG_Compound()
item_tag['tag']['HideFlags'] = nbt.TAG_Int(63) # 63 = Hide everything
# Naming
if i.customname != '':
try:
item_tag['tag']
except:
item_tag['tag'] = nbt.TAG_Compound()
item_tag['tag']['display'] = nbt.TAG_Compound()
item_tag['tag']['display']['Name'] = nbt.TAG_String(i.customname)
# Lore Text
if i.lore != '' or i.flag == 'FORTUNE':
try:
item_tag['tag']
except:
item_tag['tag'] = nbt.TAG_Compound()
try:
item_tag['tag']['display']
except:
item_tag['tag']['display'] = nbt.TAG_Compound()
item_tag['tag']['display']['Lore'] = nbt.TAG_List()
if i.flag == 'FORTUNE':
item_tag['tag']['display'][
'Name'] = nbt.TAG_String('Fortune Cookie')
i.lore = self.loadrandfortune()
loredata = textwrap.wrap(self.ConvertEscapeChars(i.lore), 30)
for loretext in loredata[:10]:
item_tag['tag']['display']['Lore'].append(
nbt.TAG_String(loretext))
else:
loredata = i.lore.split(':')
for loretext in loredata[:10]:
item_tag['tag']['display']['Lore'].append(
nbt.TAG_String(self.ConvertEscapeChars(loretext[:50])))
# Dyed
if (i.flag == 'DYED'):
try:
item_tag['tag']
except:
item_tag['tag'] = nbt.TAG_Compound()
try:
item_tag['tag']['display']
except:
item_tag['tag']['display'] = nbt.TAG_Compound()
if i.flagparam == '':
item_tag['tag']['display']['color'] = nbt.TAG_Int(
random.randint(
0,
16777215))
#.........这里部分代码省略.........