pep8 compliance changes missed because I forgot I was looking at a subset of the hits earlier

This commit is contained in:
David Sowder 2012-02-26 14:41:17 -06:00
parent 4270a929d7
commit c681391335
14 changed files with 153 additions and 153 deletions

View File

@ -57,9 +57,9 @@ class TileEntity(object):
knownIDs = baseStructures.keys() knownIDs = baseStructures.keys()
maxItems = { maxItems = {
"Furnace" : 3, "Furnace": 3,
"Chest" : 27, "Chest": 27,
"Trap" : 9, "Trap": 9,
"Cauldron": 4, "Cauldron": 4,
} }
slotNames = { slotNames = {
@ -107,28 +107,28 @@ class TileEntity(object):
class Entity(object): class Entity(object):
monsters = [ "Creeper", monsters = ["Creeper",
"Skeleton", "Skeleton",
"Spider", "Spider",
"CaveSpider", "CaveSpider",
"Giant", "Giant",
"Zombie", "Zombie",
"Slime", "Slime",
"PigZombie", "PigZombie",
"Ghast", "Ghast",
"Pig", "Pig",
"Sheep", "Sheep",
"Cow", "Cow",
"Chicken", "Chicken",
"Squid", "Squid",
"Wolf", "Wolf",
"Monster", "Monster",
"Enderman", "Enderman",
"Silverfish", "Silverfish",
"Blaze", "Blaze",
"Villager", "Villager",
"LavaSlime", "LavaSlime",
] ]
projectiles = ["Arrow", projectiles = ["Arrow",
"Snowball", "Snowball",
"Egg", "Egg",
@ -137,12 +137,12 @@ class Entity(object):
"ThrownEnderpearl", "ThrownEnderpearl",
] ]
items = [ "Item", items = ["Item",
"XPOrb", "XPOrb",
"Painting", "Painting",
"EnderCrystal", "EnderCrystal",
] ]
vehicles = [ "Minecart", "Boat" ] vehicles = ["Minecart", "Boat"]
tiles = ["PrimedTnt", "FallingSand"] tiles = ["PrimedTnt", "FallingSand"]
@classmethod @classmethod

View File

@ -93,7 +93,7 @@ class UndefinedEvent(Exception):
class Event(object): class Event(object):
"""Describe a kind of event, and its basic operations.""" """Describe a kind of event, and its basic operations."""
def __init__(self, name, null, aggregator, formatter = str): def __init__(self, name, null, aggregator, formatter=str):
self.name = name self.name = name
self._null = null self._null = null
self._aggregator = aggregator self._aggregator = aggregator
@ -545,7 +545,7 @@ class Profile(Object):
class Struct: class Struct:
"""Masquerade a dictionary with a structure-like behavior.""" """Masquerade a dictionary with a structure-like behavior."""
def __init__(self, attrs = None): def __init__(self, attrs=None):
if attrs is None: if attrs is None:
attrs = {} attrs = {}
self.__dict__['_attrs'] = attrs self.__dict__['_attrs'] = attrs
@ -623,7 +623,7 @@ XML_ELEMENT_START, XML_ELEMENT_END, XML_CHARACTER_DATA, XML_EOF = range(4)
class XmlToken: class XmlToken:
def __init__(self, type, name_or_data, attrs = None, line = None, column = None): def __init__(self, type, name_or_data, attrs=None, line=None, column=None):
assert type in (XML_ELEMENT_START, XML_ELEMENT_END, XML_CHARACTER_DATA, XML_EOF) assert type in (XML_ELEMENT_START, XML_ELEMENT_END, XML_CHARACTER_DATA, XML_EOF)
self.type = type self.type = type
self.name_or_data = name_or_data self.name_or_data = name_or_data
@ -646,7 +646,7 @@ class XmlToken:
class XmlTokenizer: class XmlTokenizer:
"""Expat based XML tokenizer.""" """Expat based XML tokenizer."""
def __init__(self, fp, skip_ws = True): def __init__(self, fp, skip_ws=True):
self.fp = fp self.fp = fp
self.tokens = [] self.tokens = []
self.index = 0 self.index = 0
@ -657,8 +657,8 @@ class XmlTokenizer:
self.character_data = '' self.character_data = ''
self.parser = xml.parsers.expat.ParserCreate() self.parser = xml.parsers.expat.ParserCreate()
self.parser.StartElementHandler = self.handle_element_start self.parser.StartElementHandler = self.handle_element_start
self.parser.EndElementHandler = self.handle_element_end self.parser.EndElementHandler = self.handle_element_end
self.parser.CharacterDataHandler = self.handle_character_data self.parser.CharacterDataHandler = self.handle_character_data
def handle_element_start(self, name, attributes): def handle_element_start(self, name, attributes):
@ -760,7 +760,7 @@ class XmlParser(Parser):
raise XmlTokenMismatch(XmlToken(XML_ELEMENT_END, name), self.token) raise XmlTokenMismatch(XmlToken(XML_ELEMENT_END, name), self.token)
self.consume() self.consume()
def character_data(self, strip = True): def character_data(self, strip=True):
data = '' data = ''
while self.token.type == XML_CHARACTER_DATA: while self.token.type == XML_CHARACTER_DATA:
data += self.token.name_or_data data += self.token.name_or_data
@ -1150,8 +1150,8 @@ class CallgrindParser(LineParser):
values = line.split(' ') values = line.split(' ')
assert len(values) == self.num_positions + self.num_events assert len(values) == self.num_positions + self.num_events
positions = values[0 : self.num_positions] positions = values[0: self.num_positions]
events = values[self.num_positions : ] events = values[self.num_positions:]
for i in range(self.num_positions): for i in range(self.num_positions):
position = positions[i] position = positions[i]
@ -1606,7 +1606,7 @@ class SharkParser(LineParser):
try: try:
entry = self.entries[function.id] entry = self.entries[function.id]
except KeyError: except KeyError:
self.entries[function.id] = (function, { }) self.entries[function.id] = (function, {})
else: else:
function_total, callees_total = entry function_total, callees_total = entry
function_total.samples += function.samples function_total.samples += function.samples
@ -1701,13 +1701,13 @@ class XPerfParser(Parser):
import csv import csv
reader = csv.reader( reader = csv.reader(
self.stream, self.stream,
delimiter = ',', delimiter=',',
quotechar = None, quotechar=None,
escapechar = None, escapechar=None,
doublequote = False, doublequote=False,
skipinitialspace = True, skipinitialspace=True,
lineterminator = '\r\n', lineterminator='\r\n',
quoting = csv.QUOTE_NONE) quoting=csv.QUOTE_NONE)
it = iter(reader) it = iter(reader)
row = reader.next() row = reader.next()
self.parse_header(row) self.parse_header(row)
@ -2053,7 +2053,7 @@ class PstatsParser:
try: try:
self.stats = pstats.Stats(*filename) self.stats = pstats.Stats(*filename)
except ValueError, e: except ValueError, e:
sys.stderr.write( "ERROR: {0}".format(e) ) sys.stderr.write("ERROR: {0}".format(e))
import hotshot.stats import hotshot.stats
self.stats = hotshot.stats.load(filename[0]) self.stats = hotshot.stats.load(filename[0])
self.profile = Profile() self.profile = Profile()
@ -2122,16 +2122,16 @@ class PstatsParser:
class Theme: class Theme:
def __init__(self, def __init__(self,
bgcolor = (0.0, 0.0, 1.0), bgcolor=(0.0, 0.0, 1.0),
mincolor = (0.0, 0.0, 0.0), mincolor=(0.0, 0.0, 0.0),
maxcolor = (0.0, 0.0, 1.0), maxcolor=(0.0, 0.0, 1.0),
fontname = "Arial", fontname="Arial",
minfontsize = 10.0, minfontsize=10.0,
maxfontsize = 10.0, maxfontsize=10.0,
minpenwidth = 0.5, minpenwidth=0.5,
maxpenwidth = 4.0, maxpenwidth=4.0,
gamma = 2.2, gamma=2.2,
skew = 1.0): skew=1.0):
self.bgcolor = bgcolor self.bgcolor = bgcolor
self.mincolor = mincolor self.mincolor = mincolor
self.maxcolor = maxcolor self.maxcolor = maxcolor
@ -2238,28 +2238,28 @@ class Theme:
return m1 return m1
TEMPERATURE_COLORMAP = Theme( TEMPERATURE_COLORMAP = Theme(
mincolor = (2.0 / 3.0, 0.80, 0.25), # dark blue mincolor=(2.0 / 3.0, 0.80, 0.25), # dark blue
maxcolor = (0.0, 1.0, 0.5), # satured red maxcolor=(0.0, 1.0, 0.5), # satured red
gamma = 1.0 gamma=1.0
) )
PINK_COLORMAP = Theme( PINK_COLORMAP = Theme(
mincolor = (0.0, 1.0, 0.90), # pink mincolor=(0.0, 1.0, 0.90), # pink
maxcolor = (0.0, 1.0, 0.5), # satured red maxcolor=(0.0, 1.0, 0.5), # satured red
) )
GRAY_COLORMAP = Theme( GRAY_COLORMAP = Theme(
mincolor = (0.0, 0.0, 0.85), # light gray mincolor=(0.0, 0.0, 0.85), # light gray
maxcolor = (0.0, 0.0, 0.0), # black maxcolor=(0.0, 0.0, 0.0), # black
) )
BW_COLORMAP = Theme( BW_COLORMAP = Theme(
minfontsize = 8.0, minfontsize=8.0,
maxfontsize = 24.0, maxfontsize=24.0,
mincolor = (0.0, 0.0, 0.0), # black mincolor=(0.0, 0.0, 0.0), # black
maxcolor = (0.0, 0.0, 0.0), # black maxcolor=(0.0, 0.0, 0.0), # black
minpenwidth = 0.1, minpenwidth=0.1,
maxpenwidth = 8.0, maxpenwidth=8.0,
) )
@ -2304,10 +2304,10 @@ class DotWriter:
label = '\n'.join(labels) label = '\n'.join(labels)
self.node(function.id, self.node(function.id,
label = label, label=label,
color = self.color(theme.node_bgcolor(weight)), color=self.color(theme.node_bgcolor(weight)),
fontcolor = self.color(theme.node_fgcolor(weight)), fontcolor=self.color(theme.node_fgcolor(weight)),
fontsize = "%.2f" % theme.node_fontsize(weight), fontsize="%.2f" % theme.node_fontsize(weight),
) )
for call in function.calls.itervalues(): for call in function.calls.itervalues():
@ -2329,13 +2329,13 @@ class DotWriter:
label = '\n'.join(labels) label = '\n'.join(labels)
self.edge(function.id, call.callee_id, self.edge(function.id, call.callee_id,
label = label, label=label,
color = self.color(theme.edge_color(weight)), color=self.color(theme.edge_color(weight)),
fontcolor = self.color(theme.edge_color(weight)), fontcolor=self.color(theme.edge_color(weight)),
fontsize = "%.2f" % theme.edge_fontsize(weight), fontsize="%.2f" % theme.edge_fontsize(weight),
penwidth = "%.2f" % theme.edge_penwidth(weight), penwidth="%.2f" % theme.edge_penwidth(weight),
labeldistance = "%.2f" % theme.edge_penwidth(weight), labeldistance="%.2f" % theme.edge_penwidth(weight),
arrowsize = "%.2f" % theme.edge_arrowsize(weight), arrowsize="%.2f" % theme.edge_arrowsize(weight),
) )
self.end_graph() self.end_graph()

View File

@ -51,7 +51,7 @@ __all__ = ["ZeroChunk", "InfdevChunk", "ChunkedLevelMixin", "MCInfdevOldLevel",
import re import re
convert = lambda text: int(text) if text.isdigit() else text convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
def sort_nicely(l): def sort_nicely(l):
@ -194,7 +194,7 @@ this way.
def latestVersion(self): def latestVersion(self):
if len(self.versions) == 0: if len(self.versions) == 0:
return None return None
return max( (v for v in self.versions if v not in self.broken_versions), key=alphanum_key) return max((v for v in self.versions if v not in self.broken_versions), key=alphanum_key)
def getJarfile(self, version=None): def getJarfile(self, version=None):
if len(self.versions) == 0: if len(self.versions) == 0:
@ -373,7 +373,7 @@ class MCServerChunkGenerator(object):
def generateAtPosition(self, tempWorld, tempDir, cx, cz): def generateAtPosition(self, tempWorld, tempDir, cx, cz):
return exhaust(self.generateAtPositionIter(tempWorld, tempDir, cx, cz)) return exhaust(self.generateAtPositionIter(tempWorld, tempDir, cx, cz))
def generateAtPositionIter(self, tempWorld, tempDir, cx, cz, simulate = False): def generateAtPositionIter(self, tempWorld, tempDir, cx, cz, simulate=False):
tempWorld.setPlayerSpawnPosition((cx * 16, 64, cz * 16)) tempWorld.setPlayerSpawnPosition((cx * 16, 64, cz * 16))
tempWorld.saveInPlace() tempWorld.saveInPlace()
tempWorld.unloadRegions() tempWorld.unloadRegions()
@ -450,10 +450,10 @@ class MCServerChunkGenerator(object):
minRadius = 5 minRadius = 5
maxRadius = 20 maxRadius = 20
def createLevel(self, level, box, simulate = False, **kw): def createLevel(self, level, box, simulate=False, **kw):
return exhaust(self.createLevelIter(level, box, simulate, **kw)) return exhaust(self.createLevelIter(level, box, simulate, **kw))
def createLevelIter(self, level, box, simulate = False, **kw): def createLevelIter(self, level, box, simulate=False, **kw):
if isinstance(level, basestring): if isinstance(level, basestring):
filename = level filename = level
level = MCInfdevOldLevel(filename, create=True, **kw) level = MCInfdevOldLevel(filename, create=True, **kw)
@ -482,7 +482,7 @@ class MCServerChunkGenerator(object):
def generateChunksInLevel(self, level, chunks): def generateChunksInLevel(self, level, chunks):
return exhaust(self.generateChunksInLevelIter(level, chunks)) return exhaust(self.generateChunksInLevelIter(level, chunks))
def generateChunksInLevelIter(self, level, chunks, simulate = False): def generateChunksInLevelIter(self, level, chunks, simulate=False):
assert isinstance(level, MCInfdevOldLevel) assert isinstance(level, MCInfdevOldLevel)
tempWorld, tempDir = self.tempWorldForLevel(level) tempWorld, tempDir = self.tempWorldForLevel(level)
@ -658,7 +658,7 @@ class InfdevChunk(LightedChunk):
return u"{region} index {index} sector {sector} length {length} format {format}".format( return u"{region} index {index} sector {sector} length {length} format {format}".format(
region=os.path.basename(self.world.regionFilename(rx, rz)), region=os.path.basename(self.world.regionFilename(rx, rz)),
sector=offset >> 8, sector=offset >> 8,
length = offset & 0xff, length=offset & 0xff,
index=4 * ((cx & 0x1f) + ((cz & 0x1f) * 32)), index=4 * ((cx & 0x1f) + ((cz & 0x1f) * 32)),
format=["???", "gzip", "deflate"][self.compressMode]) format=["???", "gzip", "deflate"][self.compressMode])
else: else:
@ -1656,7 +1656,7 @@ class ChunkedLevelMixin(object):
return slice(None, None) return slice(None, None)
return sourceMask return sourceMask
def copyBlocksFromFiniteIter(self, sourceLevel, sourceBox, destinationPoint, blocksToCopy, create = False): def copyBlocksFromFiniteIter(self, sourceLevel, sourceBox, destinationPoint, blocksToCopy, create=False):
# assumes destination point and bounds have already been checked. # assumes destination point and bounds have already been checked.
(sx, sy, sz) = sourceBox.origin (sx, sy, sz) = sourceBox.origin
@ -1725,7 +1725,7 @@ class ChunkedLevelMixin(object):
# chunk.compress(); # xxx find out why this trashes changes to tile entities # chunk.compress(); # xxx find out why this trashes changes to tile entities
def copyBlocksFromInfiniteIter(self, sourceLevel, sourceBox, destinationPoint, blocksToCopy, create = False): def copyBlocksFromInfiniteIter(self, sourceLevel, sourceBox, destinationPoint, blocksToCopy, create=False):
""" copy blocks between two infinite levels by looping through the """ copy blocks between two infinite levels by looping through the
destination's chunks. make a sub-box of the source level for each chunk destination's chunks. make a sub-box of the source level for each chunk
and copy block and entities in the sub box to the dest chunk.""" and copy block and entities in the sub box to the dest chunk."""
@ -1788,7 +1788,7 @@ class ChunkedLevelMixin(object):
sourceBox, destinationPoint = self.adjustCopyParameters(sourceLevel, sourceBox, destinationPoint) sourceBox, destinationPoint = self.adjustCopyParameters(sourceLevel, sourceBox, destinationPoint)
# needs work xxx # needs work xxx
info(u"Copying {0} blocks from {1} to {2}" .format (ly * lz * lx, sourceBox, destinationPoint)) info(u"Copying {0} blocks from {1} to {2}" .format(ly * lz * lx, sourceBox, destinationPoint))
startTime = datetime.now() startTime = datetime.now()
if not sourceLevel.isInfinite: if not sourceLevel.isInfinite:
@ -2003,7 +2003,7 @@ class ChunkedLevelMixin(object):
cx, cz = ch.chunkPosition cx, cz = ch.chunkPosition
for dx, dz in itertools.product((-1, 0, 1), (-1, 0, 1)): for dx, dz in itertools.product((-1, 0, 1), (-1, 0, 1)):
try: try:
ch = self.getChunk (cx + dx, cz + dz) ch = self.getChunk(cx + dx, cz + dz)
except (ChunkNotPresent, ChunkMalformed): except (ChunkNotPresent, ChunkMalformed):
continue continue
dirtyChunks.add(ch) dirtyChunks.add(ch)
@ -2492,7 +2492,7 @@ class MCInfdevOldLevel(ChunkedLevelMixin, EntityLevel):
def preloadDimensions(self): def preloadDimensions(self):
worldDirs = os.listdir(self.worldDir) worldDirs = os.listdir(self.worldDir)
for dirname in worldDirs : for dirname in worldDirs:
if dirname.startswith("DIM"): if dirname.startswith("DIM"):
try: try:
dimNo = int(dirname[3:]) dimNo = int(dirname[3:])
@ -2815,7 +2815,7 @@ class MCInfdevOldLevel(ChunkedLevelMixin, EntityLevel):
the chunk is done later, accesses to chunk attributes may the chunk is done later, accesses to chunk attributes may
raise ChunkMalformed""" raise ChunkMalformed"""
if not self.containsChunk(cx, cz) : if not self.containsChunk(cx, cz):
raise ChunkNotPresent((cx, cz)) raise ChunkNotPresent((cx, cz))
if not (cx, cz) in self._loadedChunks: if not (cx, cz) in self._loadedChunks:
@ -3002,7 +3002,7 @@ class MCInfdevOldLevel(ChunkedLevelMixin, EntityLevel):
r = cx >> 5, cz >> 5 r = cx >> 5, cz >> 5
rf = self.getRegionFile(*r) rf = self.getRegionFile(*r)
if rf: if rf:
rf.setOffset(cx & 0x1f , cz & 0x1f, 0) rf.setOffset(cx & 0x1f, cz & 0x1f, 0)
if (rf.offsets == 0).all(): if (rf.offsets == 0).all():
rf.close() rf.close()
os.unlink(rf.path) os.unlink(rf.path)
@ -3183,7 +3183,7 @@ class MCAlphaDimension (MCInfdevOldLevel):
if not os.path.exists(self.worldDir): if not os.path.exists(self.worldDir):
os.mkdir(self.worldDir) os.mkdir(self.worldDir)
dimensionNames = { -1: "Nether", 1: "The End"} dimensionNames = {-1: "Nether", 1: "The End"}
@property @property
def displayName(self): def displayName(self):

View File

@ -374,8 +374,8 @@ class Items (object):
with file(filename) as f: with file(filename) as f:
items_txt = f.read() items_txt = f.read()
except Exception, e: except Exception, e:
logger.info( "Error reading items.txt: %s", e) logger.info("Error reading items.txt: %s", e)
logger.info( "Using internal data." ) logger.info("Using internal data.")
items_txt = self.items_txt items_txt = self.items_txt
self.itemtypes = {} self.itemtypes = {}

View File

@ -13,7 +13,7 @@ log = logging.getLogger(__name__)
warn, error, info, debug = log.warn, log.error, log.info, log.debug warn, error, info, debug = log.warn, log.error, log.info, log.debug
def computeChunkHeightMap(materials, blocks, HeightMap = None): def computeChunkHeightMap(materials, blocks, HeightMap=None):
"""Computes the HeightMap array for a chunk, which stores the lowest """Computes the HeightMap array for a chunk, which stores the lowest
y-coordinate of each column where the sunlight is still at full strength. y-coordinate of each column where the sunlight is still at full strength.
The HeightMap array is indexed z,x contrary to the blocks array which is x,z,y. The HeightMap array is indexed z,x contrary to the blocks array which is x,z,y.
@ -496,9 +496,9 @@ class MCLevel(object):
convertedSourceBlocks, convertedSourceData = self.convertBlocksFromLevel(sourceLevel, chunk.Blocks[slices], chunk.Data[slices]) convertedSourceBlocks, convertedSourceData = self.convertBlocksFromLevel(sourceLevel, chunk.Blocks[slices], chunk.Data[slices])
destSlices = [slice(p, p + s.stop - s.start) for p, s in zip(point, slices) ] destSlices = [slice(p, p + s.stop - s.start) for p, s in zip(point, slices)]
blocks = self.Blocks[ destSlices ] blocks = self.Blocks[destSlices]
if blocksToCopy is not None: if blocksToCopy is not None:
mask = typemask[convertedSourceBlocks] mask = typemask[convertedSourceBlocks]
@ -506,7 +506,7 @@ class MCLevel(object):
blocks[mask] = convertedSourceBlocks[mask] blocks[mask] = convertedSourceBlocks[mask]
if hasattr(self, 'Data'): if hasattr(self, 'Data'):
data = self.Data[ destSlices ] data = self.Data[destSlices]
data[mask] = convertedSourceData[mask] data[mask] = convertedSourceData[mask]
yield i yield i
@ -520,7 +520,7 @@ class MCLevel(object):
sourceBox = BoundingBox(sourceBox.origin, sourceBox.size) sourceBox = BoundingBox(sourceBox.origin, sourceBox.size)
(lx, ly, lz) = sourceBox.size (lx, ly, lz) = sourceBox.size
debug(u"Asked to copy {0} blocks \n\tfrom {1} in {3}\n\tto {2} in {4}" .format (ly * lz * lx, sourceBox, destinationPoint, sourceLevel, self)) debug(u"Asked to copy {0} blocks \n\tfrom {1} in {3}\n\tto {2} in {4}" .format(ly * lz * lx, sourceBox, destinationPoint, sourceLevel, self))
# clip the source ranges to this level's edges. move the destination point as needed. # clip the source ranges to this level's edges. move the destination point as needed.
# xxx abstract this # xxx abstract this
@ -572,7 +572,7 @@ class MCLevel(object):
print "Empty source box, aborting" print "Empty source box, aborting"
return return
info(u"Copying {0} blocks from {1} to {2}" .format (sourceBox.volume, sourceBox, destinationPoint)) info(u"Copying {0} blocks from {1} to {2}" .format(sourceBox.volume, sourceBox, destinationPoint))
if not sourceLevel.isInfinite: if not sourceLevel.isInfinite:
self.copyBlocksFromFiniteToFinite(sourceLevel, sourceBox, destinationPoint, blocksToCopy) self.copyBlocksFromFiniteToFinite(sourceLevel, sourceBox, destinationPoint, blocksToCopy)
@ -799,7 +799,7 @@ class ChunkBase(EntityLevel):
def compress(self): def compress(self):
pass pass
def chunkChanged(self, needsLighting = True): def chunkChanged(self, needsLighting=True):
self.dirty = True self.dirty = True
self.needsLighting = needsLighting or self.needsLighting self.needsLighting = needsLighting or self.needsLighting

View File

@ -35,7 +35,7 @@ class Block(object):
if not isinstance(other, Block): if not isinstance(other, Block):
return -1 return -1
key = lambda a: a and (a.ID, a.blockData) key = lambda a: a and (a.ID, a.blockData)
return cmp( key(self), key(other)) return cmp(key(self), key(other))
hasVariants = False # True if blockData defines additional blocktypes hasVariants = False # True if blockData defines additional blocktypes
@ -105,7 +105,7 @@ class MCMaterials(object):
def AllStairs(self): def AllStairs(self):
return [b for b in self.allBlocks if b.name.endswith("Stairs")] return [b for b in self.allBlocks if b.name.endswith("Stairs")]
def get(self, key, default = None): def get(self, key, default=None):
try: try:
return self[key] return self[key]
except KeyError: except KeyError:
@ -284,16 +284,16 @@ alphaMaterials.addYamlBlocksFromFile("minecraft.yaml")
# --- Special treatment for some blocks --- # --- Special treatment for some blocks ---
HugeMushroomTypes = { HugeMushroomTypes = {
"Northwest" : 1, "Northwest": 1,
"North" : 2, "North": 2,
"Northeast" : 3, "Northeast": 3,
"East" : 6, "East": 6,
"Southeast" : 9, "Southeast": 9,
"South" : 8, "South": 8,
"Southwest" : 7, "Southwest": 7,
"West" : 4, "West": 4,
"Stem" : 10, "Stem": 10,
"Top" : 5, "Top": 5,
} }
from faces import * from faces import *
@ -322,7 +322,7 @@ def defineShroomFaces(Shroom, id, name):
if "east" in loway: if "east" in loway:
tex[FaceXIncreasing] = Shroom tex[FaceXIncreasing] = Shroom
alphaMaterials.addBlock(id, blockData = data, alphaMaterials.addBlock(id, blockData=data,
name="Huge " + name + " Mushroom (" + way + ")", name="Huge " + name + " Mushroom (" + way + ")",
texture=tex, texture=tex,
) )
@ -330,11 +330,11 @@ def defineShroomFaces(Shroom, id, name):
defineShroomFaces(Brown, 99, "Brown") defineShroomFaces(Brown, 99, "Brown")
defineShroomFaces(Red, 100, "Red") defineShroomFaces(Red, 100, "Red")
classicMaterials = MCMaterials(defaultName = "Not present in Classic") classicMaterials = MCMaterials(defaultName="Not present in Classic")
classicMaterials.name = "Classic" classicMaterials.name = "Classic"
classicMaterials.addYamlBlocksFromFile("classic.yaml") classicMaterials.addYamlBlocksFromFile("classic.yaml")
indevMaterials = MCMaterials(defaultName = "Not present in Indev") indevMaterials = MCMaterials(defaultName="Not present in Indev")
indevMaterials.name = "Indev" indevMaterials.name = "Indev"
indevMaterials.addYamlBlocksFromFile("classic.yaml") indevMaterials.addYamlBlocksFromFile("classic.yaml")
indevMaterials.addYamlBlocksFromFile("indev.yaml") indevMaterials.addYamlBlocksFromFile("indev.yaml")
@ -702,10 +702,10 @@ pocketMaterials.OrangeWool = pocketMaterials[115, 0]
# b.ID, b.blockData) # b.ID, b.blockData)
# for b in sorted(mats.pocketMaterials.allBlocks)]) # for b in sorted(mats.pocketMaterials.allBlocks)])
_indices = rollaxis(indices( (256, 16) ), 0, 3) _indices = rollaxis(indices((256, 16)), 0, 3)
def _filterTable(filters, unavailable, default = (0, 0) ): def _filterTable(filters, unavailable, default=(0, 0)):
# a filter table is a 256x16 table of (ID, data) pairs. # a filter table is a 256x16 table of (ID, data) pairs.
table = zeros((256, 16, 2), dtype='uint8') table = zeros((256, 16, 2), dtype='uint8')
table[:] = _indices table[:] = _indices
@ -773,11 +773,11 @@ def guessFilterTable(matsFrom, matsTo):
if block: if block:
if block != fromBlock: if block != fromBlock:
filters.append( ( (fromBlock.ID, fromBlock.blockData), (block.ID, block.blockData) ) ) filters.append(((fromBlock.ID, fromBlock.blockData), (block.ID, block.blockData)))
else: else:
unavailable.append((fromBlock.ID, fromBlock.blockData) ) unavailable.append((fromBlock.ID, fromBlock.blockData))
return filters , unavailable return filters, unavailable
allMaterials = (alphaMaterials, classicMaterials, pocketMaterials, indevMaterials) allMaterials = (alphaMaterials, classicMaterials, pocketMaterials, indevMaterials)

2
mce.py
View File

@ -1041,7 +1041,7 @@ class mce(object):
print "It is {0}:{1:02} {2} on Day {3}".format(clockHours % 12 or 12, minutes, ampm, days) print "It is {0}:{1:02} {2} on Day {3}".format(clockHours % 12 or 12, minutes, ampm, days)
else: else:
times = { "morning": 6, "noon": 12, "evening": 18, "midnight": 24 } times = {"morning": 6, "noon": 12, "evening": 18, "midnight": 24}
word = command[0] word = command[0]
minutes = 0 minutes = 0

View File

@ -104,8 +104,8 @@ if sys.platform == "win32":
print "Error while getting AppData folder using WScript.Shell.SpecialFolders: {0!r}".format(e) print "Error while getting AppData folder using WScript.Shell.SpecialFolders: {0!r}".format(e)
try: try:
from win32com.shell import shell, shellcon from win32com.shell import shell, shellcon
appDataDir = shell.SHGetPathFromIDListEx ( appDataDir = shell.SHGetPathFromIDListEx(
shell.SHGetSpecialFolderLocation (0, shellcon.CSIDL_APPDATA) shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_APPDATA)
) )
except Exception, e: except Exception, e:
print "Error while getting AppData folder using SHGetSpecialFolderLocation: {0!r}".format(e) print "Error while getting AppData folder using SHGetSpecialFolderLocation: {0!r}".format(e)

View File

@ -332,7 +332,7 @@ class PocketWorld(ChunkedLevelMixin, MCLevel):
if not 0 <= p <= 31: if not 0 <= p <= 31:
raise ChunkNotPresent((cx, cz, self)) raise ChunkNotPresent((cx, cz, self))
c = self._loadedChunks.get( (cx, cz) ) c = self._loadedChunks.get((cx, cz))
if c is None: if c is None:
c = self.chunkFile.loadChunk(cx, cz, self) c = self.chunkFile.loadChunk(cx, cz, self)
self._loadedChunks[cx, cz] = c self._loadedChunks[cx, cz] = c

View File

@ -499,15 +499,15 @@ class TAG_List(TAG_Value, collections.MutableSequence):
i.write_value(buf) i.write_value(buf)
tag_classes = { tag_classes = {
1 : TAG_Byte, 1: TAG_Byte,
2 : TAG_Short, 2: TAG_Short,
3 : TAG_Int, 3: TAG_Int,
4 : TAG_Long, 4: TAG_Long,
5 : TAG_Float, 5: TAG_Float,
6 : TAG_Double, 6: TAG_Double,
7 : TAG_Byte_Array, 7: TAG_Byte_Array,
8 : TAG_String, 8: TAG_String,
9 : TAG_List, 9: TAG_List,
10: TAG_Compound, 10: TAG_Compound,
11: TAG_Int_Array, 11: TAG_Int_Array,
12: TAG_Short_Array, 12: TAG_Short_Array,

View File

@ -106,8 +106,8 @@ def do_test(test_data, result_check, arguments=[]):
result_check = result_check.lower() result_check = result_check.lower()
env = { env = {
'MCE_RANDOM_SEED' : '42', 'MCE_RANDOM_SEED': '42',
'MCE_LAST_PLAYED' : '42', 'MCE_LAST_PLAYED': '42',
} }
if 'MCE_PROFILE' in os.environ: if 'MCE_PROFILE' in os.environ:
@ -131,8 +131,8 @@ def do_test_match_output(test_data, result_check, arguments=[]):
result_check = result_check.lower() result_check = result_check.lower()
env = { env = {
'MCE_RANDOM_SEED' : '42', 'MCE_RANDOM_SEED': '42',
'MCE_LAST_PLAYED' : '42' 'MCE_LAST_PLAYED': '42'
} }
with directory_clone(test_data) as directory: with directory_clone(test_data) as directory:

View File

@ -489,7 +489,7 @@ def adjustExtractionParameters(self, box):
if l <= 0: if l <= 0:
return return
box = BoundingBox ((x, y, z), (w, h, l)) box = BoundingBox((x, y, z), (w, h, l))
return box, (destX, destY, destZ) return box, (destX, destY, destZ)

View File

@ -7,8 +7,8 @@ ext_modules = [Extension("_nbt", ["_nbt.pyx"])]
import numpy import numpy
setup( setup(
name = 'NBT library (Cython implementation)', name='NBT library (Cython implementation)',
cmdclass = {'build_ext': build_ext}, cmdclass={'build_ext': build_ext},
ext_modules = ext_modules, ext_modules=ext_modules,
include_dirs = numpy.get_include() include_dirs=numpy.get_include()
) )

View File

@ -40,7 +40,7 @@ def mktemp(suffix):
class TempLevel(object): class TempLevel(object):
def __init__(self, filename, createFunc = None): def __init__(self, filename, createFunc=None):
if not os.path.exists(filename): if not os.path.exists(filename):
filename = join("testfiles", filename) filename = join("testfiles", filename)
tmpname = mktemp(os.path.basename(filename)) tmpname = mktemp(os.path.basename(filename))
@ -154,7 +154,7 @@ class TestNBT(unittest.TestCase):
level["Environment"]["SurroundingWaterHeight"].value += 6 level["Environment"]["SurroundingWaterHeight"].value += 6
"Save the entire TAG structure to a different file." "Save the entire TAG structure to a different file."
atlantis = TempLevel("atlantis.mclevel", createFunc = level.save) atlantis = TempLevel("atlantis.mclevel", createFunc=level.save)
def testErrors(self): def testErrors(self):
""" """
@ -306,7 +306,7 @@ class TestAlphaLevel(unittest.TestCase):
level = self.alphalevel.level level = self.alphalevel.level
cx, cz = level.allChunks.next() cx, cz = level.allChunks.next()
box = BoundingBox((cx * 16, 0, cz * 16), (38, level.Height, 25)) box = BoundingBox((cx * 16, 0, cz * 16), (38, level.Height, 25))
level.fillBlocks(box , level.materials.WoodPlanks) level.fillBlocks(box, level.materials.WoodPlanks)
c = level.getChunk(cx, cz) c = level.getChunk(cx, cz)
assert (c.Blocks == 5).all() assert (c.Blocks == 5).all()
@ -314,7 +314,7 @@ class TestAlphaLevel(unittest.TestCase):
def testReplace(self): def testReplace(self):
level = self.alphalevel.level level = self.alphalevel.level
level.fillBlocks(BoundingBox((-11, 0, -7), (38, level.Height, 25)) , level.materials.WoodPlanks, [level.materials.Dirt, level.materials.Grass]) level.fillBlocks(BoundingBox((-11, 0, -7), (38, level.Height, 25)), level.materials.WoodPlanks, [level.materials.Dirt, level.materials.Grass])
def testSaveRelight(self): def testSaveRelight(self):
indevlevel = self.indevlevel.level indevlevel = self.indevlevel.level