本文整理汇总了Python中pymclevel.nbt.load函数的典型用法代码示例。如果您正苦于以下问题:Python load函数的具体用法?Python load怎么用?Python load使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了load函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:gmcnew,项目名称:migrate-chests,代码行数:7,代码来源:migrate_chests.py
示例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
开发者ID:vongola12324,项目名称:MCEdit-Unified,代码行数:25,代码来源:nbtexplorer.py
示例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
开发者ID:BossosaurusRex,项目名称:MCEdit-Unified,代码行数:25,代码来源:nbt_test.py
示例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()
开发者ID:Aiybe,项目名称:MCEdit-Unified,代码行数:17,代码来源:anvil_test.py
示例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
开发者ID:BossosaurusRex,项目名称:MCEdit-Unified,代码行数:9,代码来源:nbt_test.py
示例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!")
开发者ID:orphu,项目名称:mcdungeon,代码行数:54,代码来源:mapstore.py
示例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
开发者ID:BossosaurusRex,项目名称:MCEdit-Unified,代码行数:14,代码来源:nbt_test.py
示例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
开发者ID:BossosaurusRex,项目名称:MCEdit-Unified,代码行数:36,代码来源:nbtexplorer.py
示例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"]
开发者ID:BossosaurusRex,项目名称:MCEdit-Unified,代码行数:17,代码来源:waypoints.py
示例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"]
开发者ID:jensz12,项目名称:MCEdit-Unified,代码行数:22,代码来源:waypoints.py
示例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!")
开发者ID:EvilSupahFly,项目名称:mcdungeon,代码行数:39,代码来源:mapstore.py
示例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([])}
开发者ID:djchrisblue,项目名称:mcdungeon,代码行数:23,代码来源:mapstore.py
示例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
开发者ID:apocalyptech,项目名称:pyinvedit,代码行数:24,代码来源:dialogs.py
示例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.'
开发者ID:TheTomcat,项目名称:mcdungeon,代码行数:36,代码来源:items.py
示例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))
#.........这里部分代码省略.........
开发者ID:DrakDragon,项目名称:mcdungeon,代码行数:101,代码来源:inventory.py
示例16: loadMapTag
def loadMapTag(level, mapid):
mapPath = level.worldFolder.getFilePath("data/map_{}.dat".format(mapid))
if os.path.exists(mapPath):
return nbt.load(mapPath)
else:
return None
开发者ID:majaha,项目名称:mcedit-filters,代码行数:6,代码来源:maprender.py
示例17: genWallMap
def genWallMap(level, box, options):
mapScale = options["Scale"]
wallMapCentreX = options["x"]
wallMapCentreZ = options["z"]
gridAlign = options["Align with Grid"]
renderMaps = options["Render Maps"]
if dimNo != 0:
dataFolder = level.parentWorld.worldFolder.getFolderPath("data")
else:
dataFolder = level.worldFolder.getFolderPath("data")
if os.path.exists(os.path.join(dataFolder, "idcounts.dat")):
idcountsTag = nbt.load(os.path.join(dataFolder, "idcounts.dat"))
# Value of last existing map, new map should be map_(mapCount+1)
mapCount = idcountsTag["map"].value
else:
mapCount = -1
if gridAlign:
wallMapCentreX = int(round(wallMapCentreX/8.0))*8
wallMapCentreZ = int(round(wallMapCentreZ/8.0))*8
# if the box is not 1 thick
if box.width != 1 and box.length != 1:
raise Exception("The selection box needs to be 1 block thick")
for chunk, slices, point in level.getChunkSlices(box):
if chunk.Blocks[slices].any():
raise Exception("The selection box should be clear of blocks")
# facing
# 0 : south, +x map left to right
# 1 : west, +z
# 2 : north, -x
# 3 : east, -z
positive = 0
negative = 0
if box.width == 1:
# wall map along y-z plane
for chunk, slices, point in level.getChunkSlices(pymclevel.box.BoundingBox(box.origin + (1, 0, 0), box.size)):
positive += chunk.Blocks[slices][chunk.Blocks[slices] != 0].size
for chunk, slices, point in level.getChunkSlices(pymclevel.box.BoundingBox(box.origin + (-1, 0, 0), box.size)):
negative += chunk.Blocks[slices][chunk.Blocks[slices] != 0].size
if positive > negative:
facing = 1
else:
facing = 3
wallMapWidth = box.length
else:
# wall map along x-y plane
for chunk, slices, point in level.getChunkSlices(pymclevel.box.BoundingBox(box.origin + (0, 0, 1), box.size)):
positive += chunk.Blocks[slices][chunk.Blocks[slices] != 0].size
for chunk, slices, point in level.getChunkSlices(pymclevel.box.BoundingBox(box.origin + (0, 0, -1), box.size)):
negative += chunk.Blocks[slices][chunk.Blocks[slices] != 0].size
if positive > negative:
facing = 2
else:
facing = 0
wallMapWidth = box.width
wallMapHeight = box.height
for chunk, slices, point in level.getChunkSlices(pymclevel.box.BoundingBox(box.origin + (1*[0, 1, 0, -1][facing], 0, 1*[-1, 0, 1, 0][facing], box.size))):
if not chunk.Blocks[slices].all():
raise Exception("The selection box should be against a wall")
def itemFramePosIter(box, facing):
if facing == 0:
return ((x, y, box.minz) for y in xrange(box.maxy-1, box.miny-1, -1) for x in xrange(box.minx, box.maxx))
elif facing == 1:
return ((box.minx, y, z) for y in xrange(box.maxy-1, box.miny-1, -1) for z in xrange(box.minz, box.maxz))
elif facing == 2:
return ((x, y, box.minz) for y in xrange(box.maxy-1, box.miny-1, -1) for x in xrange(box.maxx-1, box.minx-1, -1))
elif facing == 3:
return ((box.minx, y, z) for y in xrange(box.maxy-1, box.miny-1, -1) for z in xrange(box.maxz-1, box.minz-1, -1))
def mapCentreIter(wallMapCentreX, wallMapCentreZ, wallMapWidth, wallMapHeight, mapScale, upDir):
mapWidthInBlocks = 128 * 2**mapScale
if upDir == 2:
topLeftMapCentreX = wallMapCentreX - wallMapWidth*mapWidthInBlocks/2 + mapWidthInBlocks/2
topLeftMapCentreZ = wallMapCentreZ - wallMapHeight*mapWidthInBlocks/2 + mapWidthInBlocks/2
for h in xrange(wallMapHeight):
for w in xrange(wallMapWidth):
yield (topLeftMapCentreX + w * mapWidthInBlocks, topLeftMapCentreZ + h * mapWidthInBlocks)
elif upDir == 3:
topLeftMapCentreX = wallMapCentreX + wallMapHeight*mapWidthInBlocks/2 - mapWidthInBlocks/2
topLeftMapCentreZ = wallMapCentreZ - wallMapWidth*mapWidthInBlocks/2 + mapWidthInBlocks/2
for h in xrange(wallMapHeight):
for w in xrange(wallMapWidth):
yield (topLeftMapCentreX - h * mapWidthInBlocks, topLeftMapCentreZ + w * mapWidthInBlocks)
elif upDir == 0:
topLeftMapCentreX = wallMapCentreX + wallMapWidth*mapWidthInBlocks/2 - mapWidthInBlocks/2
topLeftMapCentreZ = wallMapCentreZ + wallMapHeight*mapWidthInBlocks/2 - mapWidthInBlocks/2
#.........这里部分代码省略.........
开发者ID:majaha,项目名称:mcedit-filters,代码行数:101,代码来源:maprender.py
示例18: testLoadNBTExplorer
def testLoadNBTExplorer():
root_tag = nbt.load("testfiles/modified_by_nbtexplorer.dat")
开发者ID:BossosaurusRex,项目名称:MCEdit-Unified,代码行数:2,代码来源:nbt_test.py
示例19: generate
#.........这里部分代码省略.........
self.position = str2Vec(cfg.offset)
self.position.x = self.position.x & ~15
self.position.z = self.position.z & ~15
# XXX bury the chest below ground
self.bury()
print "Location set to: ", self.position
# Search for a location.
else:
print "Searching for a suitable location..."
located = self.findlocation()
if (located is False):
print 'Unable to place any more treasure hunts.'
else:
print 'Treasure hunt steps: {0}'.format(self.steps)
print "Location: ", self.position
# Generate!
if (located is True):
# We have a final size, so let's initialize some things.
self.heightmap = numpy.zeros(( self.room_size,
self.room_size))
# Set the seed if requested.
if (self.args.seed is not None):
seed(self.args.seed)
print 'Seed:', self.args.seed
# Now we know the biome, we can setup a name generator
self.namegen = namegenerator.namegenerator(None, theme='pirate')
print 'Theme:', self.namegen.theme
self.owner = self.namegen.genroyalname()
print 'Owner:', self.owner
print "Location: ", self.position
print "Generating landmarks..."
self.genlandmarks()
# Name this place
if self.owner.endswith("s"):
owners = self.owner + "'"
else:
owners = self.owner + "'s"
self.dinfo['dungeon_name'] = weighted_choice( _thnames )
self.dungeon_name = self.dinfo['dungeon_name'].format(
owner=self.owner,
owners=owners)
self.dungeon_name = self.dungeon_name[:32]
self.dinfo['full_name'] = self.dungeon_name
print "Treasure hunt name:", self.dungeon_name
self.renderlandmarks()
self.placechests()
if cfg.th_spawners is True:
self.placespawners()
self.processBiomes()
# Signature
self.setblock(Vec(0, 0, 0), materials.Chest, 0, hide=True)
self.tile_ents[Vec(0, 0, 0)] = encodeTHuntInfo(self,version)
# Add to the dungeon cache.
key = '%s,%s' % (
self.position.x,
self.position.z,
)
# we need the info if making multiple hunts, to avoid
# all previous landmarks
#self.thunt_cache[key] = self.tile_ents[Vec(0, 0, 0)]
self.thunt_cache[key] = True
# copy results to the world
self.applychanges()
# Relight these chunks.
if (self.args.write is True and self.args.skiprelight is False):
# Super ugly, but does progress bars for lighting.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
h = RelightHandler()
logging.basicConfig(stream=h, level=logging.INFO)
self.world.generateLights()
h.done()
logging.getLogger().level = logging.CRITICAL
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
# Saving here allows us to pick up where we left off if we stop.
if (self.args.write is True):
print "Saving..."
self.world.saveInPlace()
saveTHuntCache(cache_path, self.thunt_cache)
saveChunkCache(cache_path, self.chunk_cache)
# make sure commandBlockOutput is false.
root_tag = nbt.load(self.world.filename)
root_tag['Data']['GameRules'][
'commandBlockOutput'].value = 'false'
root_tag.save(self.world.filename)
else:
print "Skipping save! (--write disabled)"
result = True
return result
开发者ID:HolodeckOne-Minecraft,项目名称:mcdungeon,代码行数:101,代码来源:treasure_hunt.py
示例20: load_file
def load_file():
global test_file
test_file = nbt.load(buf=test_data)
开发者ID:JavaPython,项目名称:pymclevel,代码行数:3,代码来源:time_nbt.py
注:本文中的pymclevel.nbt.load函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论