diff --git a/albow/controls.py b/albow/controls.py index bf8b36bca..67db98214 100644 --- a/albow/controls.py +++ b/albow/controls.py @@ -50,7 +50,6 @@ def set_enabled(self, x): self._enabled = x - class AttrRef(object): def __init__(self, obj, attr): self.obj = obj @@ -63,7 +62,6 @@ def set(self, x): setattr(self.obj, self.attr, x) - class ItemRef(object): def __init__(self, obj, item): self.obj = obj @@ -76,7 +74,6 @@ def set(self, x): self.obj[self.item] = x - class Label(Widget): text = overridable_property('text') align = overridable_property('align') @@ -189,7 +186,6 @@ class SmallLabel(Label): """Small text size. See theme.py""" - class ButtonBase(Control): align = 'c' action = None @@ -229,7 +225,6 @@ def __init__(self, text, action=None, enable=None, **kwds): Label.__init__(self, text, **kwds) - class Image(Widget): # image Image to display @@ -274,7 +269,6 @@ class ImageButton(ButtonBase, Image): pass - class ValueDisplay(Control, Label): format = "%s" align = 'l' @@ -311,7 +305,6 @@ def get_text(self): return self.format_value(_(self.value)) - class CheckControl(Control): def mouse_down(self, e): self.value = not self.value @@ -320,7 +313,6 @@ def get_highlighted(self): return self.value - class CheckWidget(Widget): default_size = (16, 16) margin = 4 @@ -346,12 +338,10 @@ def draw(self, surf): draw.lines(surf, fg, False, [p1, p2, p3]) - class CheckBox(CheckControl, CheckWidget): pass - class RadioControl(Control): setting = None @@ -362,6 +352,5 @@ def mouse_down(self, e): self.value = self.setting - class RadioButton(RadioControl, CheckWidget): pass diff --git a/albow/dialogs.py b/albow/dialogs.py index 262224ab3..ee0394cca 100644 --- a/albow/dialogs.py +++ b/albow/dialogs.py @@ -66,7 +66,6 @@ def key_up(self, e): pass - class QuickDialog(Dialog): """ Dialog that closes as soon as you click outside or press a key""" @@ -179,13 +178,10 @@ def ok(): def cancel(): box.dismiss(False) - buts = [] - buts.append(Button("OK", action=ok)) - buts.append(Button("Cancel", action=cancel)) + buts = [Button("OK", action=ok), Button("Cancel", action=cancel)] brow = Row(buts, spacing=d) - lb = Label(prompt) lb.topleft = (d, d) tf = TextFieldWrapped(width) diff --git a/albow/fields.py b/albow/fields.py index 9cd918c9f..264a5d6ca 100644 --- a/albow/fields.py +++ b/albow/fields.py @@ -321,7 +321,8 @@ def should_commit_immediately(self, text): class IntField(Field): tooltipText = _("Point here and use mousewheel to adjust") - def type(self, i): + @staticmethod + def type(i): try: return eval(i) except: @@ -390,7 +391,8 @@ def format_value(self, hm): def allow_char(self, c): return c in self.allowed_chars - def type(self, i): + @staticmethod + def type(i): h, m = 0, 0 i = i.upper() @@ -574,7 +576,7 @@ def draw(self, surface): lineOffsetS = startLine - self.topLine lineOffsetE = endLine - self.topLine lDiff = lineOffsetE - lineOffsetS - while lDiff > 1 and lineOffsetS + lDiff >= 0 and lineOffsetS + lDiff < self.dispLines: + while lDiff > 1 and 0 <= lDiff + lineOffsetS + lDiff < self.dispLines: y = frame.top + lineOffsetS * h + (lDiff - 1) * h rects.append(pygame.Rect(frame.left, y, frame.right - frame.left, h)) lDiff += -1 @@ -594,7 +596,7 @@ def draw(self, surface): lineOffsetE = startLine - self.topLine lineOffsetS = endLine - self.topLine lDiff = lineOffsetE - lineOffsetS - while lDiff > 1 and lineOffsetS + lDiff >= 0 and lineOffsetS + lDiff < self.dispLines: + while lDiff > 1 and 0 <= lDiff + lineOffsetS + lDiff < self.dispLines: y = frame.top + lineOffsetS * h + (lDiff - 1) * h rects.append(pygame.Rect(frame.left, y, frame.right - frame.left, h)) lDiff += -1 @@ -616,7 +618,7 @@ def draw(self, surface): # Draw Cursor if Applicable if focused and ip is not None and i is not None and il is not None: - if (self.textL): + if self.textL: x, h = font.size(self.textL[il][:i]) else: x, h = (0, font.size("X")[1]) @@ -669,7 +671,7 @@ def key_down(self, event): try: #t = pygame.scrap.get(SCRAP_TEXT).replace('\0', '') t = pyperclip.paste() - if t != None: + if t is not None: if self.insertion_point is not None: self.text = self.text[:self.insertion_point] + t + self.text[self.insertion_point:] self.insertion_point += len(t) @@ -800,7 +802,7 @@ def move_insertion_line(self, d): self.insertion_line = 0 if i is None: self.insertion_step = 0 - elif il + d >= 0 and il + d < len(self.textL): + elif 0 <= d + il + d < len(self.textL): self.insertion_line = il + d if self.insertion_line > 0: self.insertion_point = self.textRefList[self.insertion_line - 1] + self.insertion_step @@ -862,7 +864,8 @@ def insert_char(self, c): return return 'pass' - def allow_char(self, c): + @staticmethod + def allow_char(c): return True def mouse_down(self, e): @@ -911,7 +914,6 @@ def mouse_drag(self, e): else: self.selection_end = i - def pos_to_index(self, x, y): text = self.get_text() textL = self.textL @@ -927,7 +929,7 @@ def pos_to_index(self, x, y): if line >= dispLines: line = dispLines - 1 - line = line + topLine + line += topLine if line >= len(textL): line = len(textL) - 1 @@ -978,7 +980,7 @@ def updateTextWrap(self): font = self.font frame = self.get_margin_rect() frameW, frameH = frame.size - if (self.textChanged): + if self.textChanged: ix = 0 iz = 0 textLi = 0 @@ -1080,7 +1082,8 @@ def set_text(self, text): if self.should_commit_immediately(text): self.commit() - def should_commit_immediately(self, text): + @staticmethod + def should_commit_immediately(text): return False def enter_action(self): diff --git a/albow/file_dialogs.py b/albow/file_dialogs.py index df3176dfd..90cdddf20 100644 --- a/albow/file_dialogs.py +++ b/albow/file_dialogs.py @@ -13,6 +13,8 @@ from albow.palette_view import PaletteView from albow.theme import ThemeProperty from translate import _ + + class DirPathView(Widget): def __init__(self, width, client, **kwds): Widget.__init__(self, **kwds) @@ -46,7 +48,6 @@ def __init__(self, width, client, **kwds): def update(self): client = self.client dir = client.directory - suffixes = client.suffixes def filter(name): path = os.path.join(dir, name) @@ -69,7 +70,6 @@ def num_items(self): # draw.rect(surf, self.sel_color, rect) def draw_item(self, surf, item_no, rect): - font = self.font color = self.fg_color buf = self.font.render(self.names[item_no], True, color) surf.blit(buf, rect) diff --git a/albow/image_array.py b/albow/image_array.py index e87f0493e..d7d1b2cf2 100644 --- a/albow/image_array.py +++ b/albow/image_array.py @@ -20,7 +20,6 @@ def __len__(self): def __getitem__(self, index): image = self.image nrows = self.nrows - ncols = self.ncols if nrows == 1: row = 0 col = index diff --git a/albow/menu.py b/albow/menu.py index eaf489afa..992373fd5 100644 --- a/albow/menu.py +++ b/albow/menu.py @@ -105,7 +105,8 @@ def present(self, client, pos): return Dialog.present(self, centered=False) - def command_is_enabled(self, item, focus): + @staticmethod + def command_is_enabled(item, focus): cmd = item.command if cmd: enabler_name = cmd + '_enabled' diff --git a/albow/resource.py b/albow/resource.py index d8cdc2930..03d799100 100644 --- a/albow/resource.py +++ b/albow/resource.py @@ -15,9 +15,11 @@ __curLang = "default" + def getCurLang(): return __curLang + def setCurLang(lang): global __curLang __curLang = lang @@ -112,13 +114,16 @@ class DummySound(object): def fadeout(self, x): pass - def get_length(self): + @staticmethod + def get_length(): return 0.0 - def get_num_channels(self): + @staticmethod + def get_num_channels(): return 0 - def get_volume(self): + @staticmethod + def get_volume(): return 0.0 def play(self, *args): diff --git a/albow/root.py b/albow/root.py index 1b75b1472..3683955f1 100644 --- a/albow/root.py +++ b/albow/root.py @@ -118,7 +118,8 @@ def __init__(self, surface): def get_nudge_block(self): return self.selectTool.panel.nudgeBlocksButton - def set_timer(self, ms): + @staticmethod + def set_timer(ms): pygame.time.set_timer(USEREVENT, ms) def run(self): @@ -168,7 +169,6 @@ def run_modal(self, modal_widget): modal_widget.modal_result = None if not modal_widget.focus_switch: modal_widget.tab_to_first() - mouse_widget = None if clicked_widget: clicked_widget = modal_widget num_clicks = 0 @@ -265,9 +265,6 @@ def run_modal(self, modal_widget): add_modifiers(event) self.bonus_draw_time = 0 - levelExist = self.editor.level is not None - keyname = event.dict.get('keyname', None) or self.getKey(event) - self.send_key(modal_widget, 'key_down', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos @@ -280,9 +277,6 @@ def run_modal(self, modal_widget): add_modifiers(event) self.bonus_draw_time = 0 - keyname = event.dict.get('keyname', None) or self.getKey(event) - levelExist = self.editor.level is not None - self.send_key(modal_widget, 'key_up', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos @@ -342,7 +336,8 @@ def run_modal(self, modal_widget): clicked_widget = None - def getKey(self, evt=None, movement=False, keyname=None): + @staticmethod + def getKey(evt=None, movement=False, keyname=None): if keyname is None: keyname = key.name(evt.key) if 'left' in keyname and len(keyname) > 5: @@ -432,7 +427,8 @@ def remove_idle_handler(self, widget): self.idle_handlers.remove(ref(widget)) - def send_key(self, widget, name, event): + @staticmethod + def send_key(widget, name, event): widget.dispatch_key(name, event) def begin_frame(self): @@ -446,7 +442,7 @@ def get_root(self): def show_tooltip(self, widget, pos): if hasattr(self, 'currentTooltip'): - if self.currentTooltip != None: + if self.currentTooltip is not None: self.remove(self.currentTooltip) self.currentTooltip = None @@ -500,10 +496,12 @@ def quit(self): self.capture_mouse(None) sys.exit(0) - def confirm_quit(self): + @staticmethod + def confirm_quit(): return True - def get_mouse_for(self, widget): + @staticmethod + def get_mouse_for(widget): last = last_mouse_event event = Event(0, last.dict) event.dict['local'] = widget.global_to_local(event.pos) @@ -521,7 +519,8 @@ def gl_clear(self): GL.glClearColor(r, g, b, 0.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) - def music_end(self): + @staticmethod + def music_end(): import music music.music_end() diff --git a/albow/tab_panel.py b/albow/tab_panel.py index 9c78bb3e9..5553b72ea 100644 --- a/albow/tab_panel.py +++ b/albow/tab_panel.py @@ -168,7 +168,6 @@ def gl_draw(self, root, offset): if len(pages) > 1: tlcorner = (offset[0] + self.bottomleft[0], offset[1] + self.bottomleft[1]) - pageTabContents = [] current_page = self.current_page n = len(pages) b = self.tab_border_width @@ -176,7 +175,6 @@ def gl_draw(self, root, offset): h = self.tab_height m = self.tab_margin tabWidth = (self.size[0] - (s * n) - (2 * m)) / n - width = self.width - 2 * m + s - b x0 = m + tlcorner[0] font = self.tab_font @@ -192,7 +190,7 @@ def gl_draw(self, root, offset): glColor(1.0, 1.0, 1.0, 0.5) else: glColor(0.5, 0.5, 0.5, 0.5) - glRectf(x0, tlcorner[1] - (m + b), x1, tlcorner[1] - (h)) + glRectf(x0, tlcorner[1] - (m + b), x1, tlcorner[1] - h) buf = font.render(self.pages[i].tab_title, True, self.fg_color or fg) r = buf.get_rect() diff --git a/albow/table_view.py b/albow/table_view.py index 18cb62fab..6c7329543 100644 --- a/albow/table_view.py +++ b/albow/table_view.py @@ -45,8 +45,8 @@ def __init__(self, nrows=15, height=None, Column.__init__(self, contents, align='l', spacing=s, **kwds) if header: header.font = self.header_font or self.font - header.fg_color = fg_color = self.header_fg_color or self.fg_color - header.bg_color = bg_color = self.header_bg_color or self.bg_color + header.fg_color = self.header_fg_color or self.fg_color + header.bg_color = self.header_bg_color or self.bg_color rows.font = self.font rows.fg_color = self.fg_color rows.bg_color = self.bg_color @@ -78,13 +78,15 @@ def draw_text_cell(self, surf, i, data, cell_rect, align, font): buf = font.render(unicode(data), True, self.fg_color) blit_in_rect(surf, buf, cell_rect, align) - def row_is_selected(self, n): + @staticmethod + def row_is_selected(n): return False def click_row(self, n, e): pass - def click_column_header(self, col): + @staticmethod + def click_column_header(col): print "click_column_header: ", col def click_header(self, n, e): @@ -170,7 +172,7 @@ def __init__(self, width, height): # self.parent.draw_header_cell(surf, i, text, cell_rect, column) def row_data(self, row): - None + pass def draw_table_cell(self, surf, i, data, cell_rect, column): self.parent.draw_header_cell(surf, i, cell_rect, column) diff --git a/albow/translate.py b/albow/translate.py index e565e9a72..8976239a9 100644 --- a/albow/translate.py +++ b/albow/translate.py @@ -57,6 +57,8 @@ import resource import platform, locale + + def getPlatInfo(**kwargs): """kwargs: dict: {"module_name": module,...} used to display version information about modules.""" @@ -121,6 +123,7 @@ def getPlatInfo(**kwargs): #------------------------------------------------------------------------------- # Translation loading and mapping functions #------------------------------------------------------------------------------- + def _(string, doNotTranslate=False): """Returns the translated 'string', or 'string' itself if no translation found.""" if doNotTranslate: @@ -137,6 +140,7 @@ def _(string, doNotTranslate=False): return trn or string #------------------------------------------------------------------------------- + def loadTemplate(fName="template.trn"): """Load the template fName file in the global template variable. Returns the template.""" @@ -187,6 +191,7 @@ def loadTemplate(fName="template.trn"): return template #------------------------------------------------------------------------------- + def saveTemplate(): if buildTemplate: fName = os.path.abspath(os.path.join(getLangPath(), "template.trn")) @@ -219,21 +224,23 @@ def setLangPath(path): return False #------------------------------------------------------------------------------- + def getLangPath(): """...""" return langPath #------------------------------------------------------------------------------- + def getLang(): return lang + def setLang(newlang): """Set the actual language. Returns old and new languages and string_cache in a tulpe. newlang: str: new laguage to load in the format _""" global lang oldLang = "" + lang - result = False if not lang == newlang: sc, result = buildTranslation(newlang) lang = newlang @@ -245,7 +252,7 @@ def setLang(newlang): #------------------------------------------------------------------------------- def correctEncoding(data, oldEnc="ascii", newEnc=enc): """Returns encoded/decoded data.""" - return data # disabled for now, but can be use full in the future + return data # disabled for now, but can be use full in the future if type(data) == str: data = data.decode(newEnc) elif type(data) == unicode: @@ -286,6 +293,8 @@ def getLangName(file, path=None): from time import asctime, time #------------------------------------------------------------------------------- + + def buildTranslation(lang,suppressAlert=False): """Finds the file corresponding to 'lang' builds up string_cache. If the file is not valid, does nothing. @@ -320,6 +329,7 @@ def buildTranslation(lang,suppressAlert=False): grps2 = re.findall(r"^t\d+[ ]", data, re.M|re.S) log.warning(" Unpaired original and translated strings. %s is longer (oXX: %s, tXX: %s)."%({True: "tXX", False: "oXX"}[len(grps1) < len(grps2)], len(grps1), len(grps2))) bugStrs = [] + def compLists(lst1, lst1N, lst2, lst2N, repl, bugStrs=bugStrs): bug = [] for item in lst1: diff --git a/albow/tree.py b/albow/tree.py index 57ed5fe24..ea9b6a1a8 100644 --- a/albow/tree.py +++ b/albow/tree.py @@ -96,7 +96,6 @@ def build_layout(self): keys.sort() items = [[0, a, data[a], parent, children, keys.index(a) + 1] for a in keys] rows = [] - level = 0 w = 50 aId = len(items) + 1 while items: @@ -105,7 +104,7 @@ def build_layout(self): fields = [] if type(v) in self.compound_types: meth = getattr(self, 'parse_%s'%v.__class__.__name__, None) - if not meth is None: + if meth is not None: v = meth(k, v) ks = v.keys() ks.sort() @@ -185,7 +184,8 @@ def draw_tree_cell(self, surf, i, data, cell_rect, column): else: self.draw_image_cell(surf, i, data, cell_rect, column) - def draw_image_cell(self, surf, i, data, cell_rect, column): + @staticmethod + def draw_image_cell(surf, i, data, cell_rect, column): """...""" blit_in_rect(surf, data, cell_rect, 'l') diff --git a/albow/utils.py b/albow/utils.py index 0a7a155d6..80b612978 100644 --- a/albow/utils.py +++ b/albow/utils.py @@ -21,7 +21,6 @@ def blit_tinted(surface, image, pos, tint, src_rect=None): src_rgb = array3d(image) buf_rgb = pixels3d(buf) buf_rgb[...] = minimum(255, add(tint, src_rgb)).astype('b') - buf_rgb = None surface.blit(buf, pos) diff --git a/albow/widget.py b/albow/widget.py index 9d7b760e2..eb7532dbd 100644 --- a/albow/widget.py +++ b/albow/widget.py @@ -89,6 +89,7 @@ class Widget(object): tooltip = None tooltipText = None doNotTranslate = False + def __init__(self, rect=None, **kwds): if rect and not isinstance(rect, Rect): raise TypeError("Widget rect not a pygame.Rect") @@ -562,7 +563,8 @@ def invalidate(self): if self.root: self.root.bonus_draw_time = 0 - def get_cursor(self, event): + @staticmethod + def get_cursor(event): return arrow_cursor def predict(self, kwds, name): @@ -740,7 +742,7 @@ def gl_draw_all(self, root, offset): else: try: surface = Surface(self.size, SRCALPHA) - except Exception, e: + except Exception: #size error? return self.draw_all(surface) diff --git a/bresenham.py b/bresenham.py index 7415d2f5e..c97b4a6f8 100644 --- a/bresenham.py +++ b/bresenham.py @@ -1,7 +1,6 @@ def bresenham(p1, p2): """Bresenham line algorithm adapted for 3d. slooooow.""" - steep = 0 coords = [] x, y, z = p1 x2, y2, z2 = p2 @@ -39,10 +38,10 @@ def bresenham(p1, p2): for j in otherAxes: while d[j] >= 0: - p[j] = p[j] + sp[j] - d[j] = d[j] - (2 * dl[longestAxis]) + p[j] += sp[j] + d[j] -= 2 * dl[longestAxis] - p[longestAxis] = p[longestAxis] + sp[longestAxis] + p[longestAxis] += sp[longestAxis] d = map(lambda a, b: a + 2 * b, d, dl) return coords # added by me diff --git a/config.py b/config.py index 55d0eaf44..e88e1771d 100644 --- a/config.py +++ b/config.py @@ -43,15 +43,17 @@ def __init__(self, definitions): def __getitem__(self, section): return self._sections[section] - def getPath(self): + @staticmethod + def getPath(): return directories.configFilePath - def transformKey(self, value, i=0): + @staticmethod + def transformKey(value, i=0): if 'left' in value and len(value) > 5: value = value[5:] elif 'right' in value and len(value) > 6: value = value[6:] - if value >= 'a' and value <= 'z': + if 'a' <= value <= 'z': value = value.replace(value[0], value[0].upper(), 1) if i >= 36 and "Ctrl-" not in value: value = "Ctrl-" + value @@ -67,7 +69,8 @@ def transformKey(self, value, i=0): value = "Button 5" return value - def convert(self, key): + @staticmethod + def convert(key): vals = key.replace('-', ' ').translate(None, '()').lower().split(' ') return vals[0] + "".join(x.title() for x in vals[1:]) @@ -353,8 +356,6 @@ def copy(self): k.keyorder = list(self.keyorder) return k - - # Quick Reference: # 7 Bedrock # 9 Still_Water diff --git a/directories.py b/directories.py index 10dd2d104..85e3a38ec 100644 --- a/directories.py +++ b/directories.py @@ -72,16 +72,13 @@ def fsdecode(x): return x.decode(sys.getfilesystemencoding()) argzero = fsdecode(os.path.abspath(sys.argv[0])) - if argzero.endswith('.exe'): - dataDir = os.path.dirname(fsdecode(sys.executable)) - else: - dataDir = os.path.dirname(argzero) dataDir = os.getcwdu() else: dataDir = os.getcwdu() return dataDir + def win32_appdata(): # try to use win32 api to get the AppData folder since python doesn't populate os.environ with unicode strings. @@ -103,6 +100,7 @@ def win32_appdata(): return os.environ['APPDATA'].decode(sys.getfilesystemencoding()) + def getMinecraftProfileJSON(): """Returns a dictionary object with the minecraft profile information""" if os.path.isfile(os.path.join(getMinecraftLauncherDirectory(), "launcher_profiles.json")): @@ -135,9 +133,8 @@ def getMinecraftLauncherDirectory(): else: return os.path.expanduser("~/.minecraft") -def getDocumentsFolder(): - docsFolder = None +def getDocumentsFolder(): if sys.platform == "win32": try: import win32com.client @@ -149,7 +146,7 @@ def getDocumentsFolder(): print e try: docsFolder = shell.SHGetFolderPath(0, shellcon.CSIDL_MYDOCUMENTS, 0, 0) - except Exception, e: + except Exception: userprofile = os.environ['USERPROFILE'].decode(sys.getfilesystemencoding()) docsFolder = os.path.join(userprofile, "Documents") @@ -164,6 +161,7 @@ def getDocumentsFolder(): return docsFolder + def getSelectedProfile(): ''' Gets the selected profile from the Minecraft Launcher @@ -229,7 +227,6 @@ def goPortable(): brushesDir = portableBrushesDir configFilePath = portableConfigFilePath filtersDir = portableFiltersDir - jarStorageDir = portableJarStorageDir portable = True return True @@ -275,17 +272,14 @@ def goFixed(): brushesDir = fixedBrushesDir configFilePath = fixedConfigFilePath filtersDir = fixedFiltersDir - jarStorageDir = fixedJarStorageDir portable = False - - def fixedConfigExists(): if sys.platform == "darwin": return True # Check for files at portable locations. Cannot be Mac because config doesn't move - return (os.path.exists(fixedConfigFilePath) or not os.path.exists(portableConfigFilePath)) + return os.path.exists(fixedConfigFilePath) or not os.path.exists(portableConfigFilePath) if fixedConfigExists(): @@ -318,6 +312,7 @@ def fixedConfigExists(): #else: # serverJarStorageDir = fixedJarStorageDir + def getAllOfAFile(file_dir, ext): ''' Returns a list of all the files the direcotry with the specified file extenstion @@ -326,6 +321,7 @@ def getAllOfAFile(file_dir, ext): ''' return glob.glob(file_dir+"/*"+ext) + def getCacheDir(): """Returns the path to the cache folder. This folder is the Application Support folder on OS X, and the Documents Folder on Windows.""" if sys.platform == "win32": diff --git a/drawable.py b/drawable.py index ed6b9fc21..a124ca79f 100644 --- a/drawable.py +++ b/drawable.py @@ -16,14 +16,16 @@ def __init__(self): self.invalidList = True self.children = [] - def setUp(self): + @staticmethod + def setUp(): """ Set up rendering settings and view matrices :return: :rtype: """ - def tearDown(self): + @staticmethod + def tearDown(): """ Return any settings changed in setUp to their previous states :return: diff --git a/editortools/blockpicker.py b/editortools/blockpicker.py index 7cb349db7..5f7d10153 100644 --- a/editortools/blockpicker.py +++ b/editortools/blockpicker.py @@ -69,7 +69,7 @@ def formatBlockName(x): def formatBlockID(x): block = self.matchingBlocks[x] - ident = "({id}:{data})".format (id=block.ID, data=block.blockData) + ident = "({id}:{data})".format(id=block.ID, data=block.blockData) return ident tableview = TableView(columns=[TableColumn(" ", 24, "l", lambda x: ""), @@ -199,11 +199,6 @@ def textEntered(self): blocks = self.materials.allBlocks - matches = blocks - oldBlock = self.materials.Air - if len(self.matchingBlocks): - oldBlock = self.matchingBlocks[self.selectedBlockIndex] - if len(text): matches = self.materials.blocksMatching(text) if blockData: diff --git a/editortools/brush.py b/editortools/brush.py index 8a83c59a3..cbc705800 100644 --- a/editortools/brush.py +++ b/editortools/brush.py @@ -58,6 +58,7 @@ log = logging.getLogger(__name__) + class BrushOperation(Operation): def __init__(self, tool): super(BrushOperation, self).__init__(tool.editor, tool.editor.level) @@ -99,7 +100,8 @@ def _perform(): brushBox = self.tool.getDirtyBox(point, self.tool) brushBoxThisChunk, slices = chunk.getChunkSlicesForBox(brushBox) f = self.brushMode.applyToChunkSlices(self.brushMode, self, chunk, slices, brushBox, brushBoxThisChunk) - if brushBoxThisChunk.volume == 0: f = None + if brushBoxThisChunk.volume == 0: + f = None if hasattr(f, "__iter__"): for progress in f: yield progress @@ -111,6 +113,7 @@ def _perform(): else: exhaust(_perform()) + class BrushPanel(Panel): def __init__(self, tool): Panel.__init__(self) @@ -186,11 +189,12 @@ def createField(self, key, value): self.tool.recentBlocks[key] = [] wcb = getattr(self.tool.brushMode, 'wildcardBlocks', []) aw = False - if key in wcb: aw = True + if key in wcb: + aw = True object = BlockButton(self.tool.editor.level.materials, ref=reference, - recentBlocks = self.tool.recentBlocks[key], - allowWildcards = aw + recentBlocks=self.tool.recentBlocks[key], + allowWildcards=aw ) else: if doNotTranslate: @@ -216,7 +220,8 @@ def brushModeChanged(self): self.tool.setupPreview() self.tool.showPanel() - def getBrushFileList(self): + @staticmethod + def getBrushFileList(): """ Returns a list of strings of all .preset files in the brushes directory. """ @@ -330,7 +335,6 @@ def presetSelected(self): return else: self.tool.loadBrushPreset(choice) - choice = "Load Preset" self.tool.showPanel() @@ -353,6 +357,7 @@ def __init__(self, tool): self.shrink_wrap() return + class BrushTool(CloneTool): tooltipText = "Brush\nRight-click for options" toolIconName = "brush" @@ -385,7 +390,6 @@ def __init__(self, *args): self.lineToolKey = False self.root = get_root() - """ Property reticleOffset. Used to determine the distance between the block the cursor is pointing at, and the center of the brush. @@ -397,6 +401,7 @@ def reticleOffset(self): if getattr(self.brushMode, 'draggableBrush', True): return self._reticleOffset return 0 + @reticleOffset.setter def reticleOffset(self, val): self._reticleOffset = val @@ -407,20 +412,25 @@ def reticleOffset(self, val): @property def W(self): return self.options['W'] + @W.setter def W(self, val): self.options['W'] = val self.setupPreview() + @property def H(self): return self.options['H'] + @H.setter def H(self, val): self.options['H'] = val self.setupPreview() + @property def L(self): return self.options['L'] + @L.setter def L(self, val): self.options['L'] = val @@ -439,7 +449,6 @@ def statusText(self): G=config.keys.rollBrush.get(), ) - def toolEnabled(self): """ Brush tool is always enabled on the toolbar. @@ -497,7 +506,7 @@ def tryImport(self, name, dir): else: embeded = True try: - path = os.path.join(dir, (name+ ".py")) + path = os.path.join(dir, (name + ".py")) if type(path) == unicode and DEF_ENC != "UTF-8": path = path.encode(DEF_ENC) globals()[name] = m = imp.load_source(name, path) @@ -520,7 +529,6 @@ def tryImport(self, name, dir): alert(_(u"Exception while importing brush mode {}. See console for details.\n\n{}").format(name, e)) return object() - def toolSelected(self): """ Applies options of BrushToolOptions. @@ -536,7 +544,8 @@ def toolSelected(self): key = getattr(self.brushMode, 'mainBlock', 'Block') wcb = getattr(self.brushMode, 'wildcardBlocks', []) aw = False - if key in wcb: aw = True + if key in wcb: + aw = True blockPicker = BlockPicker(self.options[key], self.editor.level.materials, allowWildcards=aw) if blockPicker.present(): self.options[key] = blockPicker.blockInfo @@ -556,8 +565,6 @@ def toolSelected(self): else: self.loadLevel(stack[0]) - - def saveBrushPreset(self, name): """ Saves current brush presets in a file name.preset @@ -577,7 +584,7 @@ def saveBrushPreset(self, name): else: optionsToSave[key] = self.options[key] optionsToSave["Mode"] = getattr(self, 'selectedBrushMode', 'Fill') - name = name + ".preset" + name += ".preset" f = open(os.path.join(directories.brushesDir, name), "w") f.write(repr(optionsToSave)) @@ -586,8 +593,7 @@ def loadBrushPreset(self, name): Loads a brush preset name.preset :param name, name of the preset to load. """ - name = name+'.preset' - finish = True + name += '.preset' try: f = open(os.path.join(directories.brushesDir, name), "r") except: @@ -620,14 +626,13 @@ def loadBrushPreset(self, name): self.showPanel() self.setupPreview() - @property def worldTooltipText(self): """ Displays the corresponding tooltip if ALT is pressed. Called by leveleditor every tick. """ - if self.pickBlockKey == True: + if self.pickBlockKey: try: if self.editor.blockFaceUnderCursor is None: return @@ -638,7 +643,6 @@ def worldTooltipText(self): except Exception, e: return repr(e) - def keyDown(self, evt): """ Triggered on pressing a key, @@ -669,7 +673,7 @@ def mouseDown(self, evt, pos, direction): Sets bllockButton if pickBlock is True. Also starts dragging. """ - if self.pickBlockKey == True: + if self.pickBlockKey: id = self.editor.level.blockAt(*pos) data = self.editor.level.blockDataAt(*pos) key = getattr(self.brushMode, 'mainBlock', 'Block') @@ -722,7 +726,6 @@ def mouseUp(self, evt, pos, direction): """ if 0 == len(self.draggedPositions): return - size = self.getBrushSize() op = BrushOperation(self) self.editor.addOperation(op) if op.canUndo: @@ -751,13 +754,13 @@ def toolReselected(self): key = getattr(self.brushMode, 'mainBlock', 'Block') wcb = getattr(self.brushMode, 'wildcardBlocks', []) aw = False - if key in wcb: aw = True + if key in wcb: + aw = True blockPicker = BlockPicker(self.options[key], self.editor.level.materials, allowWildcards=aw) if blockPicker.present(): self.options[key] = blockPicker.blockInfo self.setupPreview() - def showPanel(self): """ Removes old panels. @@ -804,7 +807,7 @@ def getBrushSize(self): """ size = [] if getattr(self.brushMode, 'disableStyleButton', False): - return (1,1,1) + return 1,1,1 for dim in ['W','H','L']: size.append(self.options[dim]) return size @@ -879,7 +882,7 @@ def increaseToolReach(self): """ if self.editor.mainViewport.mouseMovesCamera and not self.editor.longDistanceMode: return False - self.reticleOffset = self.reticleOffset + 1 + self.reticleOffset += 1 return True def decreaseToolReach(self): @@ -893,7 +896,6 @@ def decreaseToolReach(self): self.reticleOffset = max(self.reticleOffset - 1, 0) return True - def drawToolReticle(self): """ Draws a yellow reticle at every position where you dragged the brush. @@ -929,7 +931,7 @@ def drawTerrainReticle(self): self.setupPreview() self.renderedBlock = self.options[getattr(self.brushMode, 'mainBlock', 'Block')] - if self.pickBlockKey == 1: #Alt is pressed + if self.pickBlockKey == 1: #Alt is pressed self.editor.drawWireCubeReticle(color=(0.2, 0.6, 0.9, 1.0)) else: pos, direction = self.editor.blockFaceUnderCursor @@ -942,7 +944,7 @@ def drawTerrainReticle(self): GL.glVertex3f(*map(lambda a, b: a + 0.5 + b * 0.5, pos, direction)) #Top side of surface block dirtyBox = self.getDirtyBox(reticlePoint, self) self.drawTerrainPreview(dirtyBox.origin) - if self.lineToolKey == True and len(self.draggedPositions) and getattr(self.brushMode, 'draggableBrush', True): #If dragging mouse with Linetool pressed. + if self.lineToolKey and len(self.draggedPositions) and getattr(self.brushMode, 'draggableBrush', True): #If dragging mouse with Linetool pressed. GL.glColor4f(1.0, 1.0, 1.0, 0.7) with gl.glBegin(GL.GL_LINES): GL.glVertex3f(*map(lambda a: a + 0.5, self.draggedPositions[0])) @@ -961,7 +963,7 @@ def increaseBrushSize(self): Decreases Brush Size, triggered by pressing corresponding key. """ for key in ('W', 'H', 'L'): - self.options[key] = self.options[key] + 1 + self.options[key] += 1 self.setupPreview() def swap(self): @@ -1026,7 +1028,7 @@ def importPaste(self): if clipFilename: try: self.loadLevel(pymclevel.fromFile(clipFilename, readonly=True)) - except Exception, e: + except Exception: alert("Failed to load file %s" % clipFilename) self.brushMode = "Fill" return @@ -1087,7 +1089,6 @@ def createBrushMask(shape, style="Round", offset=(0, 0, 0), box=None, chance=100 elif style == "Cylinder": pass - elif style == "Square": # mask = ones(outputShape, dtype=bool) # mask = blockCenters[:, newaxis, newaxis, newaxis] < shape @@ -1103,7 +1104,7 @@ def createBrushMask(shape, style="Round", offset=(0, 0, 0), box=None, chance=100 distances = sum(blockCenters, 0) mask = distances < 1 else: - raise ValueError, "Unknown style: " + style + raise ValueError("Unknown style: " + style) if (chance < 100 or hollow) and max(shape) > 1: threshold = chance / 100.0 diff --git a/editortools/clone.py b/editortools/clone.py index 8a429f2c8..28e722b4c 100644 --- a/editortools/clone.py +++ b/editortools/clone.py @@ -141,7 +141,8 @@ def perform(self, recordUndo=True): create=True, biomes=self.copyBiomes, staticCommands=self.staticCommands, moveSpawnerPos=self.moveSpawnerPos, regenerateUUID=self.regenerateUUID, first=False) showProgress(_("Copying {0:n} blocks...").format(self.sourceBox.volume), i) - def bufferSize(self): + @staticmethod + def bufferSize(): return 123456 @@ -225,6 +226,7 @@ def redo(self): super(CloneOperation, self).redo() [i.redo() for i in self.selectionOps] + class CloneToolPanel(Panel): useOffsetInput = True @@ -290,7 +292,7 @@ def __init__(self, tool, editor, _parent=None): iv = scaleField.increase_value def scaleFieldDecrease(): - if scaleField.value > 1 / 8.0 and scaleField.value <= 1.0: + if 1 / 8.0 < scaleField.value <= 1.0: scaleField.value *= 0.5 else: dv() @@ -711,7 +713,8 @@ def rotatedSelectionSize(self): # return self.editor.selectionTool.selectionBox() # # =========================================================================== - def getBlockAt(self): + @staticmethod + def getBlockAt(): return None # use level's blockAt def getReticleOrigin(self): @@ -733,8 +736,8 @@ def getReticleOrigin(self): x, y, z = map(lambda p, s: p - s / 2, pos, size) if self.chunkAlign: - x = x & ~0xf - z = z & ~0xf + x &= ~0xf + z &= ~0xf sy = size[1] if sy > lev.Height: # don't snap really tall stuff to the height @@ -778,7 +781,7 @@ def drawTerrainReticle(self): if self.level is None: return - if self.destPoint != None: + if self.destPoint is not None: destPoint = self.destPoint if self.draggingFace is not None: # debugDrawPoint() @@ -849,7 +852,7 @@ def drawRepeatedCube(self, box, color): def drawToolMarkers(self): selectionBox = self.selectionBox() - if (selectionBox): + if selectionBox: widg = self.editor.find_widget(pygame.mouse.get_pos()) try: if self.panel and (widg is self.panel.nudgeButton or widg.parent is self.panel.nudgeButton): @@ -907,7 +910,7 @@ def flip(self, amount=1, blocksOnly=False): def mirror(self, blocksOnly=False): if self.canRotateLevel: yaw = int(self.editor.mainViewport.yaw) % 360 - if (yaw >= 45 and yaw < 135) or (yaw > 225 and yaw <= 315): + if (45 <= yaw < 135) or (225 < yaw <= 315): if blocksOnly: self.level.flipEastWestBlocks() else: @@ -1115,6 +1118,7 @@ def confirm(self): self.destPoint = None self.level = None + def discardPreviewer(self): if self.previewRenderer is None: return @@ -1127,6 +1131,7 @@ def discardPreviewer(self): class ConstructionToolPanel(CloneToolPanel): useOffsetInput = False + class ConstructionToolOptions(ToolOptions): def __init__(self, tool): Panel.__init__(self) @@ -1144,6 +1149,7 @@ def __init__(self, tool): self.add(col) self.shrink_wrap() + class ConstructionTool(CloneTool): surfaceBuild = True toolIconName = "crane" diff --git a/editortools/editortool.py b/editortools/editortool.py index 27a994a33..71ef32cd2 100644 --- a/editortools/editortool.py +++ b/editortools/editortool.py @@ -204,7 +204,6 @@ def pointInBounds(point, x): # return the away-facing face dim = face // 2 - side = face & 1 dim1, dim2 = dim + 1, dim + 2 dim1, dim2 = dim1 % 3, dim2 % 3 diff --git a/editortools/fill.py b/editortools/fill.py index 32daa1044..8d195f50e 100644 --- a/editortools/fill.py +++ b/editortools/fill.py @@ -273,7 +273,7 @@ def mirror(self, amount=1, blocksOnly=False): id = [self._blockInfo.ID] data = [self._blockInfo.blockData] yaw = int(self.editor.mainViewport.yaw) % 360 - if (yaw >= 45 and yaw < 135) or (yaw > 225 and yaw <= 315): + if (45 <= yaw < 135) or (225 < yaw <= 315): FlipEastWest(id,data) else: FlipNorthSouth(id,data) diff --git a/editortools/filter.py b/editortools/filter.py index 6423d4d00..90fd759fb 100644 --- a/editortools/filter.py +++ b/editortools/filter.py @@ -87,7 +87,6 @@ def __init__(self, tool, module, *args, **kw): pages.is_gl_container = True self.pages = pages self.optionDict = {} - pageTabContents = [] self.giveEditorObject(module) print "Creating options for ", module @@ -109,7 +108,7 @@ def __init__(self, tool, module, *args, **kw): self.add(pages) self.shrink_wrap() if len(pages.pages): - if (pages.current_page != None): + if pages.current_page is not None: pages.show_page(pages.current_page) else: pages.show_page(pages.pages[0]) @@ -122,7 +121,6 @@ def makeTabPage(self, tool, inputs, trn=None): page.is_gl_container = True rows = [] cols = [] - height = 0 max_height = self.tool.editor.mainViewport.height - self.tool.updatePanel.height - self._parent.filterSelectRow.height - self._parent.confirmButton.height - self.pages.tab_height page.optionDict = {} page.tool = tool @@ -161,7 +159,6 @@ def makeTabPage(self, tool, inputs, trn=None): splitWord = keyword.split('=') if len(splitWord) > 1: v = None - key = None try: v = int(splitWord[1]) @@ -170,9 +167,7 @@ def makeTabPage(self, tool, inputs, trn=None): key = splitWord[0] if v is not None: - if key == "lines": - lin = v - elif key == "width": + if key == "width": wid = v else: if key == "value": @@ -226,7 +221,7 @@ def makeTabPage(self, tool, inputs, trn=None): elif optionType == "string": input = None # not sure how to pull values from filters, but leaves it open for the future. Use this variable to set field width. - if input != None: + if input is not None: size = input else: size = 200 @@ -259,7 +254,7 @@ def makeTabPage(self, tool, inputs, trn=None): page.add(Row(cols)) page.shrink_wrap() - return (title, page, page._rect) + return title, page, page._rect @property def options(self): @@ -318,7 +313,6 @@ def reload(self): if not self._recording: self.macro_button = Button("Record a Macro", action=self.start_record_macro) - filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255)) filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir()) @@ -351,11 +345,9 @@ def reload(self): if self.selectedFilterName in self.savedOptions: self.filterOptionsPanel.options = self.savedOptions[self.selectedFilterName] - def run_macro(self): self.tool.run_macro(self.macro_data) - - + def reload_macro(self): self.usingMacro = True for i in list(self.subwidgets): @@ -383,8 +375,7 @@ def reload_macro(self): self.shrink_wrap() if self.parent: self.centery = self.parent.centery - - + def filterChanged(self): if not self.filterSelect.selectedChoice.startswith("[Macro]"): self.saveOptions() @@ -394,13 +385,11 @@ def filterChanged(self): self.saveOptions() self.selectedFilterName = self.filterSelect.selectedChoice self.reload_macro() - def set_save(self): self._save_macro = True self.macro_diag.dismiss() - - + def stop_record_macro(self): self.macro_diag = Dialog() @@ -422,12 +411,9 @@ def stop_record_macro(self): try: macro_dict = json.load(open(os.path.join(directories.getCacheDir(), "macros.json"), 'rb')) except ValueError: - macro_dict = {} - macro_dict["Macros"] = {} - self.tool + macro_dict = {"Macros": {}} else: - macro_dict = {} - macro_dict["Macros"] = {} + macro_dict = {"Macros": {}} macro_dict["Macros"][macroNameField.get_text()] = {} macro_dict["Macros"][macroNameField.get_text()]["Number of steps"] = len(self.macro_steps) for entry in self.macro_steps: @@ -438,8 +424,7 @@ def stop_record_macro(self): with open(os.path.join(directories.getCacheDir(), "macros.json"), 'w') as f: json.dump(macro_dict, f) self.reload() - - + def start_record_macro(self): self.macro_steps = [] self.current_step = 0 @@ -450,11 +435,8 @@ def start_record_macro(self): self._recording = True def addMacroStep(self, name=None, inputs=None): - data = {} - data["Name"] = name - data["Step"] = self.current_step - data["Inputs"] = inputs - self.current_step = self.current_step + 1 + data = {"Name": name, "Step": self.current_step, "Inputs": inputs} + self.current_step += 1 self.macro_steps.append(data) filterOptionsPanel = None @@ -486,7 +468,6 @@ def perform(self, recordUndo=True): else: self.panel.addMacroStep(name=self.panel.filterSelect.selectedChoice, inputs=self.options) self.wasMacroOperation = True - self.canUndo = True pass @@ -553,15 +534,15 @@ def updateFilters(self): except OSError: pass for module in self.filterModules.values(): - totalFilters = totalFilters + 1 + totalFilters += 1 if hasattr(module, "UPDATE_URL") and hasattr(module, "VERSION"): if isinstance(module.UPDATE_URL, (str, unicode)) and isinstance(module.VERSION, (str, unicode)): versionJSON = json.loads(urllib2.urlopen(module.UPDATE_URL).read()) if module.VERSION != versionJSON["Version"]: urllib.urlretrieve(versionJSON["Download-URL"], os.path.join(filtersDir, "updates", versionJSON["Name"])) - updatedFilters = updatedFilters + 1 - for f in os.listdir(os.path.join(filtersDir ,"updates")): + updatedFilters += 1 + for f in os.listdir(os.path.join(filtersDir, "updates")): shutil.copy(os.path.join(filtersDir, "updates", f), filtersDir) shutil.rmtree(os.path.join(filtersDir, "updates")) self.finishedUpdatingWidget = Widget() @@ -579,7 +560,6 @@ def closeFinishedUpdatingWidget(self): def reloadFilters(self): if self.filterModules: for k, m in self.filterModules.iteritems(): - name = m.__name__ del m mceutils.compareMD5Hashes(directories.getAllOfAFile(directories.filtersDir, ".py")) @@ -620,7 +600,8 @@ def tryImport(name): def filterNames(self): return [self.moduleDisplayName(module) for module in self.filterModules.itervalues()] - def moduleDisplayName(self, module): + @staticmethod + def moduleDisplayName(module): if hasattr(module, "displayName"): if hasattr(module, "trn"): return module.trn._(module.displayName) @@ -669,4 +650,3 @@ def run_macro(self, macro_steps): self.editor.addOperation(op) self.editor.addUnsavedEdit() self.editor.invalidateBox(self.selectionBox()) - diff --git a/editortools/nbtexplorer.py b/editortools/nbtexplorer.py index f589a3da5..32d80759d 100644 --- a/editortools/nbtexplorer.py +++ b/editortools/nbtexplorer.py @@ -70,10 +70,12 @@ def click_item(self, *args, **kwargs): if self._parent: self._parent.update_side_panel(self.selected_item) - def draw_square(self, surf, bg, r): + @staticmethod + def draw_square(surf, bg, r): draw.polygon(surf, bg, [r.topleft, r.topright, r.bottomright, r.bottomleft]) - def draw_circle(self, surf, bg, r): + @staticmethod + def draw_circle(surf, bg, r): draw.circle(surf, bg, ((r.left + r.right) / 2, (r.top + r.bottom) / 2), min(r.height / 2, r.width / 2)) def draw_TAG_bullet(self, surf, bg, fg, shape, text): @@ -142,8 +144,7 @@ def __init__(self, editor): ], margin=0, spacing=2) col.shrink_wrap() - row = [col,] - row.append(Column([Label("", width=300),], height=max_height)) + row = [col, Column([Label("", width=300), ], height=max_height)] self.add(Column([header, Row(row)])) self.shrink_wrap() self.side_panel = None @@ -195,8 +196,6 @@ def update_side_panel(self, item): rows.append(Row([Label("Data Type:"), Label(t)])) if type(itm) in field_types.keys(): f, bounds = field_types[type(itm)] - if f == TextFieldWrapped: - field = f(text=itm.value, width=300) if bounds: field = f(text="%s"%itm.value, min=bounds[0], max=bounds[1]) else: @@ -216,8 +215,8 @@ def update_side_panel(self, item): # col.shrink_wrap() self.side_panel = col - - def build_attributes(self, items): + @staticmethod + def build_attributes(items): rows = [] attributes = items[0] names = [a['Name'].value for a in attributes] @@ -239,7 +238,8 @@ def build_attributes(self, items): def build_motion(self, items): return self.build_pos(items) - def build_pos(self, items): + @staticmethod + def build_pos(items): rows = [] pos = items[0] rows.append(Row([Label("X", align='l'), Label("%s"%pos[0].value, align='l')])) @@ -247,7 +247,8 @@ def build_pos(self, items): rows.append(Row([Label("Z", align='l'), Label("%s"%pos[2].value, align='l')])) return rows - def build_rotation(self, items): + @staticmethod + def build_rotation(items): rows = [] rotation = items[0] rows.append(Row([Label("Y", align='l'), Label("%s"%rotation[0].value, align='l')])) @@ -282,20 +283,25 @@ def build_inventory(self, items): table.rows.tooltipText = "Double-click to edit" table.selected_row = None table.slots = slots + def num_rows(): return len(slots) table.num_rows = num_rows + def row_data(n): return slots[n] table.row_data = row_data + def click_row(n, e): table.selected_row = n if e.num_clicks > 1: SlotEditor(table, row_data(n)).present() table.click_row = click_row + def row_is_selected(n): return n == table.selected_row table.row_is_selected = row_is_selected + def change_value(data): s, i, c, d = data table.slots[s] = slots[s] = data @@ -313,6 +319,7 @@ def change_value(data): class NBTExplorerTool(EditorTool): """...""" tooltipText = "Dive into level NBT structure." + def __init__(self, editor): """...""" self.toolIconName = 'nbtexplorer' diff --git a/editortools/operation.py b/editortools/operation.py index ff38d6d02..630b1b9fb 100644 --- a/editortools/operation.py +++ b/editortools/operation.py @@ -74,7 +74,8 @@ def _extractUndo(): return undoLevel - def extractUndoSchematic(self, level, box): + @staticmethod + def extractUndoSchematic(level, box): if box.volume > 131072: sch = showProgress("Recording undo...", level.extractZipSchematicIter(box), cancel=True) else: @@ -86,7 +87,6 @@ def extractUndoSchematic(self, level, box): return sch - # represents a single undoable operation def perform(self, recordUndo=True): " Perform the operation. Record undo information if recordUndo" @@ -135,7 +135,6 @@ def _redo(): else: exhaust(_redo()) - def dirtyBox(self): """ The region modified by the operation. Return None to indicate no blocks were changed. diff --git a/editortools/player.py b/editortools/player.py index 27122798f..55915228d 100644 --- a/editortools/player.py +++ b/editortools/player.py @@ -33,6 +33,7 @@ log = logging.getLogger(__name__) + class PlayerRemoveOperation(Operation): undoTag = None @@ -104,6 +105,7 @@ def undo(self): def redo(self): self.perform() + class PlayerAddOperation(Operation): playerTag = None @@ -125,7 +127,7 @@ def perform(self, recordUndo=True): return try: self.uuid = version_utils.playercache.getPlayerFromPlayername(self.player) - self.player = version_utils.playercache.getPlayerFromUUID(self.uuid) #Case Corrected + self.player = version_utils.playercache.getPlayerFromUUID(self.uuid) #Case Corrected except: action = ask("Could not get {}'s UUID. Please make sure that you are connected to the internet and that the player {} exists.".format(self.player, self.player), ["Enter UUID manually", "Cancel"]) if action != "Enter UUID manually": @@ -290,7 +292,8 @@ def redo(self): level.setPlayerOrientation(self.redoYP, self.player) self.tool.markerList.invalidate() - def bufferSize(self): + @staticmethod + def bufferSize(): return 20 @@ -467,7 +470,6 @@ def movePlayerToCamera(self): pos = self.editor.mainViewport.cameraPosition y = self.editor.mainViewport.yaw p = self.editor.mainViewport.pitch - d = self.editor.level.dimNo op = PlayerMoveOperation(self, pos, player, (y, p)) self.movingPlayer = None @@ -668,7 +670,7 @@ def drawCharacterHead(self, x, y, z, realCoords=None): size = (0.5, 0.5, 0.5) box = FloatBox(origin, size) - if realCoords != None and self.playerPos[realCoords] != "Player": + if realCoords is not None and self.playerPos[realCoords] != "Player": drawCube(box, texture=self.playerTexture[self.playerPos[realCoords]], textureVertices=self.texVerts) else: @@ -676,7 +678,6 @@ def drawCharacterHead(self, x, y, z, realCoords=None): texture=self.charTex, textureVertices=self.texVerts) GL.glDisable(GL.GL_CULL_FACE) - #@property #def statusText(self): # if not self.panel: @@ -700,7 +701,7 @@ def mouseDown(self, evt, pos, direction): if self.recordMove: self.editor.addOperation(op) else: - self.editor.performWithRetry(op) #Prevent recording of Undo when adding player + self.editor.performWithRetry(op) #Prevent recording of Undo when adding player self.recordMove = True self.editor.addUnsavedEdit() diff --git a/editortools/select.py b/editortools/select.py index ded3deeb0..bddf623a8 100644 --- a/editortools/select.py +++ b/editortools/select.py @@ -139,7 +139,7 @@ def __init__(self, tool, editor): deleteTileTicksButton.tooltipText = "Removes all tile ticks within selection. Tile ticks are scheduled block updates" # deleteTileEntitiesButton = Button("Delete TileEntities", action=self.tool.deleteTileEntities) analyzeButton = Button("Analyze", action=self.tool.analyzeSelection) - analyzeButton.tooltipText ="Count the different blocks and entities in the selection and display the totals." + analyzeButton.tooltipText = "Count the different blocks and entities in the selection and display the totals." cutButton = Button("Cut", action=self.tool.cutSelection) cutButton.tooltipText = _("Take a copy of all blocks and entities within the selection, then delete everything within the selection. Shortcut: {0}").format( config.keys.cut.get()) @@ -297,7 +297,6 @@ def worldTooltipText(self): box = self.selectionBoxInProgress() if box: size = "{s[0]} W x {s[2]} L x {s[1]} H".format(s=box.size) - text = size if size: return size elif self.dragResizeFace is not None: @@ -305,8 +304,6 @@ def worldTooltipText(self): else: return self.describeBlockAt(pos) - return text.strip() - except Exception, e: return repr(e) @@ -713,7 +710,7 @@ def selectOtherCorner(self): def drawToolMarkers(self): selectionBox = self.selectionBox() - if (selectionBox): + if selectionBox: widg = self.editor.find_widget(pygame.mouse.get_pos()) # these corners stay even while using the chunk tool. @@ -721,7 +718,7 @@ def drawToolMarkers(self): lineWidth = 3 for t, c, n in ((self.bottomLeftPoint, self.bottomLeftColor, self.bottomLeftNudge), (self.topRightPoint, self.topRightColor, self.topRightNudge)): - if t != None: + if t is not None: (sx, sy, sz) = t if self.selectionInProgress: if t == self.getSelectionPoint(self.currentCorner): @@ -737,7 +734,7 @@ def drawToolMarkers(self): alpha = 0.4 try: bt = self.editor.level.blockAt(sx, sy, sz) - if (bt): + if bt: alpha = 0.2 except (EnvironmentError, pymclevel.ChunkNotPresent): pass @@ -746,7 +743,7 @@ def drawToolMarkers(self): lineWidth += 1 # draw highlighted block faces when nudging - if (widg.parent == n or widg == n): + if widg.parent == n or widg == n: GL.glEnable(GL.GL_BLEND) nudgefaces = numpy.array([ selectionBox.minx, selectionBox.miny, selectionBox.minz, @@ -859,7 +856,7 @@ def drawToolMarkers(self): if self.dragResizeFace is not None: self.showPanel() # xxx do this every frame while dragging because our UI kit is bad - if ((self.selectionInProgress or self.clickSelectionInProgress) and otherCorner != None): + if (self.selectionInProgress or self.clickSelectionInProgress) and otherCorner is not None: GL.glPolygonOffset(DepthOffset.PotentialSelection, DepthOffset.PotentialSelection) pos, direction = self.editor.blockFaceUnderCursor @@ -892,7 +889,7 @@ def drawToolReticle(self): try: bt = self.editor.level.blockAt(*pos) - if (bt): + if bt: # # textureCoords = materials[bt][0] alpha = 0.12 except (EnvironmentError, pymclevel.ChunkNotPresent): @@ -920,8 +917,9 @@ def setSelection(self, box): else: self.setSelectionPoints(self.selectionPointsFromBox(box)) - def selectionPointsFromBox(self, box): - return (box.origin, map(lambda x: x - 1, box.maximum)) + @staticmethod + def selectionPointsFromBox(box): + return box.origin, map(lambda x: x - 1, box.maximum) def selectNone(self): self.setSelectionPoints(None) @@ -1001,6 +999,7 @@ def deleteTileTicks(self, recordUndo=True): self.editor.freezeStatus("Removing Tile Ticks...") level = self.editor.level editor = self.editor + class DeleteTileTicksOperation(Operation): def __init__(self, editor, level): self.editor = editor @@ -1031,7 +1030,6 @@ def redo(self): if op.canUndo: self.editor.addUnsavedEdit() - @alertException def deleteEntities(self, recordUndo=True): box = self.selectionBox() diff --git a/editortools/thumbview.py b/editortools/thumbview.py index e42def1a6..bc910e387 100644 --- a/editortools/thumbview.py +++ b/editortools/thumbview.py @@ -107,5 +107,5 @@ def blockInfo(self, b): self.add(self.thumb) self.thumb.size = self.size self.thumb.drawBackground = False - for i in self.thumb.renderer.chunkWorker: + for _ in self.thumb.renderer.chunkWorker: pass diff --git a/glutils.py b/glutils.py index 9efba241c..4711cea6e 100644 --- a/glutils.py +++ b/glutils.py @@ -114,15 +114,15 @@ def __del__(self): self.invalidate() @classmethod - def invalidateAllLists(self): + def invalidateAllLists(cls): allLists = [] - for listref in self.allLists: + for listref in cls.allLists: list = listref() if list: list.invalidate() allLists.append(listref) - self.allLists = allLists + cls.allLists = allLists def invalidate(self): if self._list: diff --git a/hook-updater4pyi.py b/hook-updater4pyi.py index 8b3122859..d2ec6044c 100644 --- a/hook-updater4pyi.py +++ b/hook-updater4pyi.py @@ -24,4 +24,4 @@ def locpath(x): # from hookutils import collect_data_files #datas = collect_data_files('updater4pyi') -print "DATAS IS\n\t%r" % (datas) +print "DATAS IS\n\t%r" % datas diff --git a/keys.py b/keys.py index 946edf71a..7e671ad16 100644 --- a/keys.py +++ b/keys.py @@ -8,12 +8,14 @@ ESCAPE = '\033' + def remapMouseButton(button): buttons = [0, 1, 3, 2, 4, 5, 6, 7] # mouse2 is right button, mouse3 is middle if button < len(buttons): return buttons[button] return button + class KeyConfigPanel(Dialog): keyConfigKeys = [ "", @@ -373,7 +375,6 @@ class KeyConfigPanel(Dialog): ("Fast Increment Modifier", "Shift") ]} - selectedKeyIndex = 0 def __init__(self): @@ -476,7 +477,8 @@ def getRowData(self, i): key = "" return configKey, key - def isConfigKey(self, configKey): + @staticmethod + def isConfigKey(configKey): return not (len(configKey) == 0 or configKey[0] == "<") def selectTableRow(self, i, evt): diff --git a/leveleditor.py b/leveleditor.py index 893cdf294..8235dde85 100644 --- a/leveleditor.py +++ b/leveleditor.py @@ -206,32 +206,24 @@ def __init__(self, mcedit): get_value=lambda: _("MBv: %0.1f") % (self.renderer.bufferUsage / 1000000.), tooltipText="Memory used for vertexes") - def showViewOptions(): - col = [] - col.append(mceutils.CheckBoxLabel("Entities", fg_color=(0xff, 0x22, 0x22), - ref=config.settings.drawEntities)) - col.append( - mceutils.CheckBoxLabel("Items", fg_color=(0x22, 0xff, 0x22), ref=config.settings.drawItems)) - col.append(mceutils.CheckBoxLabel("TileEntities", fg_color=(0xff, 0xff, 0x22), - ref=config.settings.drawTileEntities)) - col.append(mceutils.CheckBoxLabel("TileTicks", ref=config.settings.drawTileTicks)) - col.append(mceutils.CheckBoxLabel("Unpopulated Chunks", fg_color=renderer.TerrainPopulatedRenderer.color, - ref=config.settings.drawUnpopulatedChunks)) - col.append(mceutils.CheckBoxLabel("Chunks Borders", fg_color=renderer.ChunkBorderRenderer.color, - ref=config.settings.drawChunkBorders)) - - col.append(mceutils.CheckBoxLabel("Sky", ref=config.settings.drawSky)) - col.append(mceutils.CheckBoxLabel("Fog", ref=config.settings.drawFog)) - col.append(mceutils.CheckBoxLabel("Ceiling", - ref=config.settings.showCeiling)) - - col.append(mceutils.CheckBoxLabel("Chunk Redraw", fg_color=(0xff, 0x99, 0x99), - ref=config.settings.showChunkRedraw)) - - col.append(mceutils.CheckBoxLabel("Hidden Ores", - ref=config.settings.showHiddenOres, - tooltipText="Check to show/hide specific ores using the settings below.")) + col = [mceutils.CheckBoxLabel("Entities", fg_color=(0xff, 0x22, 0x22), + ref=config.settings.drawEntities), + mceutils.CheckBoxLabel("Items", fg_color=(0x22, 0xff, 0x22), ref=config.settings.drawItems), + mceutils.CheckBoxLabel("TileEntities", fg_color=(0xff, 0xff, 0x22), + ref=config.settings.drawTileEntities), + mceutils.CheckBoxLabel("TileTicks", ref=config.settings.drawTileTicks), + mceutils.CheckBoxLabel("Unpopulated Chunks", fg_color=renderer.TerrainPopulatedRenderer.color, + ref=config.settings.drawUnpopulatedChunks), + mceutils.CheckBoxLabel("Chunks Borders", fg_color=renderer.ChunkBorderRenderer.color, + ref=config.settings.drawChunkBorders), + mceutils.CheckBoxLabel("Sky", ref=config.settings.drawSky), + mceutils.CheckBoxLabel("Fog", ref=config.settings.drawFog), mceutils.CheckBoxLabel("Ceiling", + ref=config.settings.showCeiling), + mceutils.CheckBoxLabel("Chunk Redraw", fg_color=(0xff, 0x99, 0x99), + ref=config.settings.showChunkRedraw), mceutils.CheckBoxLabel("Hidden Ores", + ref=config.settings.showHiddenOres, + tooltipText="Check to show/hide specific ores using the settings below.")] for ore in config.settings.hiddableOres.get(): col.append(mceutils.CheckBoxLabel(self.level.materials[ore].name.replace(" Ore", ""), @@ -334,7 +326,8 @@ def viewMode(self, val): self.chunkViewport.size = self.mainViewport.size = self.viewportContainer.size self.renderer.loadNearbyChunks() - def swapViewports(self): + @staticmethod + def swapViewports(): if config.settings.viewMode.get() == "Chunk": config.settings.viewMode.set("Camera") else: @@ -346,7 +339,8 @@ def addCopiedSchematic(self, sch): self.deleteCopiedSchematic(self.copyStack[-1]) self.updateCopyPanel() - def _deleteSchematic(self, sch): + @staticmethod + def _deleteSchematic(sch): if hasattr(sch, 'close'): sch.close() if sch.filename and os.path.exists(sch.filename): @@ -446,7 +440,7 @@ def createOneCopyPanel(sch, i): panel.pages.append(Column(page, spacing=2, align="l")) panel.pages[-1].shrink_wrap() page = [p] - if page != []: + if page: panel.pages.append(Column(page, spacing=2, align="l")) panel.pages[-1].shrink_wrap() @@ -473,7 +467,6 @@ def changeCopyPage(this, delta): page.parent = this.subwidgets[0].subwidgets[1] else: page.visible = False - page = this.pages[self.currentCopyPage] pb = this.subwidgets[0].subwidgets[0].subwidgets[0] nb = this.subwidgets[0].subwidgets[0].subwidgets[1] if self.currentCopyPage == 0: @@ -655,7 +648,6 @@ def YesNoWidget(self, msg): waiter = None while waiter is None: if self.user_yon_response is not None: - waiter = True return self.user_yon_response def yes(self): @@ -722,7 +714,6 @@ def addNumField(wid, name, val, minimum=None, maximum=None, increment=0.1): splitWord = word.split('=') if len(splitWord) > 1: v = None - key = None try: v = int(splitWord[1]) @@ -731,9 +722,7 @@ def addNumField(wid, name, val, minimum=None, maximum=None, increment=0.1): key = splitWord[0] if v is not None: - if key == "lines": - lin = v - elif key == "width": + if key == "width": width = v else: if key == "value": @@ -776,7 +765,7 @@ def addNumField(wid, name, val, minimum=None, maximum=None, increment=0.1): elif inputType == "string": input = None - if input != None: + if input is not None: size = input else: size = 200 @@ -809,8 +798,8 @@ def addNumField(wid, name, val, minimum=None, maximum=None, increment=0.1): else: return "user canceled" - - def Notify(self, msg): + @staticmethod + def Notify(msg): ask(msg, ["Close"], cancel=0) def reloadToolbar(self): @@ -842,7 +831,8 @@ def reloadToolbar(self): longDistanceMode = config.settings.longDistanceMode.property() - def genSixteenBlockTexture(self): + @staticmethod + def genSixteenBlockTexture(): has12 = GL.glGetString(GL.GL_VERSION) >= "1.2" if has12: maxLevel = 2 @@ -888,7 +878,8 @@ def makeSixteenBlockTex(): return Texture(makeSixteenBlockTex, mode) - def showProgress(self, *a, **kw): + @staticmethod + def showProgress(*a, **kw): return mceutils.showProgress(*a, **kw) def drawConstructionCube(self, box, color, texture=None): @@ -1140,8 +1131,9 @@ def saveFile(self): self.freezeStatus("Saving...") chunks = self.level.chunkCount count = [0] + def copyChunks(): - for i in self.level.saveInPlaceGen(): + for _ in self.level.saveInPlaceGen(): count[0] += 1 yield count[0],chunks @@ -1459,7 +1451,8 @@ def drawStars(self): fractionalReachAdjustment = True - def postMouseMoved(self): + @staticmethod + def postMouseMoved(): evt = event.Event(MOUSEMOTION, rel=(0, 0), pos=mouse.get_pos(), buttons=mouse.get_pressed()) event.post(evt) @@ -1510,7 +1503,8 @@ def take_screenshot(self): self.diag.shrink_wrap() self.diag.present() - def open_screenshots_folder(self): + @staticmethod + def open_screenshots_folder(): platform_open(os.path.join(directories.parentDir, "screenshots")) def screenshot_notify(self): @@ -1520,9 +1514,9 @@ def key_up(self, evt): self.currentTool.keyUp(evt) keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) try: - keyname = self.different_keys[keyname] + keyname = self.different_keys[keyname] except: - pass + pass if keyname == config.keys.brake.get(): self.mainViewport.brakeOff() @@ -1540,9 +1534,9 @@ def key_down(self, evt): self.currentTool.keyDown(evt) keyname = evt.dict.get('keyname', None) or self.root.getKey(evt) try: - keyname = self.different_keys[keyname] + keyname = self.different_keys[keyname] except: - pass + pass if keyname == "Alt-F4": self.quit() @@ -1816,6 +1810,7 @@ def composeMCTime(d, h, m, t): items.append(Row([Label("Format:"),formatLabel])) nameField = TextFieldWrapped(width=300, value=self.level.LevelName) + def alt21(): nameField.insertion_point = len(nameField.text) nameField.insert_char(u'\xa7') @@ -1862,7 +1857,6 @@ def action(): b = Button(gametype(t), action=action) b.gametype = t - gametypeRow = Row((Label("Game Type: "), b)) items.append(gametypeRow) if isinstance(self.level, pymclevel.MCInfdevOldLevel): @@ -2278,13 +2272,13 @@ def undo(self): self.freezeStatus("Undoing the previous operation...") wasSelectionBox = False if self.selectionBox(): - wasSelectionBox = True + wasSelectionBox = True if len(self.undoStack) > 0: op = self.undoStack.pop() normalUndo = True else: - op = self.afterSaveUndoStack.pop() - normalUndo = False + op = self.afterSaveUndoStack.pop() + normalUndo = False if self.recordUndo: self.redoStack.append(op) @@ -2295,13 +2289,13 @@ def undo(self): if changedBox is not None: self.invalidateBox(changedBox) if not self.selectionBox() and wasSelectionBox: - self.toolbar.selectTool(0) - self.toolbar.tools[0].currentCorner = 1 + self.toolbar.selectTool(0) + self.toolbar.tools[0].currentCorner = 1 if ".SelectionOperation" not in str(op) and ".NudgeSelectionOperation" not in str(op): if normalUndo: self.removeUnsavedEdit() else: - self.addUnsavedEdit() + self.addUnsavedEdit() self.root.fix_sticky_ctrl() @@ -2537,10 +2531,12 @@ def drawWireCubeReticle(self, color=(1.0, 1.0, 1.0, 1.0), position=None): GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) - def drawString(self, x, y, color, string): + @staticmethod + def drawString(x, y, color, string): return - def freezeStatus(self, string): + @staticmethod + def freezeStatus(string): return # GL.glColor(1.0, 0., 0., 1.0) @@ -2709,7 +2705,7 @@ def handleMemoryError(self): self.level.compressAllChunks() self.toolbar.selectTool(0) - self.renderer.viewDistance = self.renderer.viewDistance - 4 + self.renderer.viewDistance -= 4 self.renderer.discardAllChunks() logging.warning( @@ -2789,7 +2785,7 @@ def mouse_down(self, evt): self.showToolOptions(toolNo) def showToolOptions(self, toolNumber): - if toolNumber < len(self.tools) and toolNumber >= 0: + if len(self.tools) > toolNumber >= 0: t = self.tools[toolNumber] # if not t.toolEnabled(): # return @@ -2808,7 +2804,7 @@ def selectTool(self, toolNumber): self.parent.currentTool.toolReselected() else: self.parent.selectionTool.hidePanel() - if self.parent.currentTool != None: + if self.parent.currentTool is not None: self.parent.currentTool.cancel() self.parent.currentTool = t self.parent.currentTool.toolSelected() @@ -2875,7 +2871,7 @@ def drawToolbar(self): if tool.toolIconName is None: continue try: - if not tool.toolIconName in self.toolTextures: + if tool.toolIconName not in self.toolTextures: filename = "toolicons" + os.sep + "{0}.png".format(tool.toolIconName) self.toolTextures[tool.toolIconName] = mceutils.loadPNGTexture(filename) x = 20 * i + 4 diff --git a/mce.py b/mce.py index 0e6e6270e..59f360542 100644 --- a/mce.py +++ b/mce.py @@ -155,14 +155,16 @@ def commandUsage(self, command): debug = False needsSave = False - def readInt(self, command): + @staticmethod + def readInt(command): try: val = int(command.pop(0)) except ValueError: raise UsageError("Cannot understand numeric input") return val - def prettySplit(self, command): + @staticmethod + def prettySplit(command): cmdstring = " ".join(command) lex = shlex.shlex(cmdstring) @@ -275,7 +277,8 @@ def readBlockInfo(self, command): return blockInfo - def readBlocksToCopy(self, command): + @staticmethod + def readBlocksToCopy(command): blocksToCopy = range(materials.id_limit) while len(command): word = command.pop() @@ -287,7 +290,8 @@ def readBlocksToCopy(self, command): return blocksToCopy - def _box(self, command): + @staticmethod + def _box(command): """ Boxes: @@ -328,7 +332,8 @@ def _debug(self, command): self.debug = not self.debug print "Debug", ("disabled", "enabled")[self.debug] - def _log(self, command): + @staticmethod + def _log(command): """ log [ ] @@ -450,7 +455,6 @@ def _analyze(self, command): Counts all of the block types in every chunk of the world. """ blockCounts = zeros((65536,), 'uint64') - sizeOnDisk = 0 print "Analyzing {0} chunks...".format(self.level.chunkCount) # for input to bincount, create an array of uint16s by @@ -1065,7 +1069,7 @@ def _time(self, command): if ticks < 0: ticks += 18000 - ampm = ("AM", "PM")[hours > 11 and hours < 24] + ampm = ("AM", "PM")[11 < hours < 24] print "Changed time to {0}:{1:02} {2}".format(hours % 12 or 12, minutes, ampm) self.level.Time = ticks self.needsSave = True @@ -1181,7 +1185,7 @@ def _heightmap(self, command): c = self.level.getChunk(cx, cz) imgarray = numpy.asarray(greyimg.crop((cz * 16, cx * 16, cz * 16 + 16, cx * 16 + 16))) - imgarray = imgarray / 2 # scale to 0-127 + imgarray /= 2 # scale to 0-127 for x in range(16): for z in range(16): @@ -1329,13 +1333,11 @@ def _blocks(self, command): With nothing, prints a list of all blocks. """ - searchName = None if len(command): searchName = " ".join(command) try: searchNumber = int(searchName) except ValueError: - searchNumber = None matches = self.level.materials.blocksMatching(searchName) else: matches = [b for b in self.level.materials.allBlocks if b.ID == searchNumber] @@ -1402,7 +1404,7 @@ def run(self): try: world = raw_input("Please enter world name or path to world folder: ") self.loadWorld(world) - except EOFError, e: + except EOFError: print "End of input." raise SystemExit except Exception, e: @@ -1420,7 +1422,6 @@ def run(self): else: # process many commands on standard input, maybe interactively - command = [""] self.batchMode = True while True: try: @@ -1428,7 +1429,7 @@ def run(self): print self.processCommand(command) - except EOFError, e: + except EOFError: print "End of file. Saving automatically." self._save([]) raise SystemExit @@ -1452,7 +1453,7 @@ def processCommand(self, command): commandWords = command.split() keyword = commandWords.pop(0).lower() - if not keyword in self.commands: + if keyword not in self.commands: matches = filter(lambda x: x.startswith(keyword), self.commands) if len(matches) == 1: keyword = matches[0] diff --git a/mcedit.py b/mcedit.py index 5ce12ab46..5c91caf57 100644 --- a/mcedit.py +++ b/mcedit.py @@ -219,7 +219,8 @@ def loadRecentWorldNumber(self, i): numRecentWorlds = 5 - def removeLevelDat(self, filename): + @staticmethod + def removeLevelDat(filename): if filename.endswith("level.dat"): filename = os.path.dirname(filename) return filename @@ -244,21 +245,21 @@ def addRecentWorld(self, filename): rw = [filename] + rw[:self.numRecentWorlds - 1] self.setRecentWorlds(rw) - def setRecentWorlds(self, worlds): + @staticmethod + def setRecentWorlds(worlds): for i, filename in enumerate(worlds): config.config.set("Recent Worlds", str(i), filename.encode('utf-8')) def makeSideColumn(self): def showLicense(): platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt")) + def showCacheDir(): platform_open(directories.getCacheDir()) def showScreenshotsDir(): platform_open(os.path.join(directories.parentDir, "screenshots")) - readmePath = os.path.join(directories.getDataDir(), "README.html") - hotkeys = ([("", "Controls", self.showKeyConfig), @@ -396,13 +397,14 @@ def saveAndQuit(self): self.editor.saveFile() raise SystemExit - def justQuit(self): + @staticmethod + def justQuit(): raise SystemExit @classmethod - def fetch_version(self): - with self.version_lock: - self.version_info = release.fetch_new_version_info() + def fetch_version(cls): + with cls.version_lock: + cls.version_info = release.fetch_new_version_info() def check_for_version(self): new_version = release.check_for_new_version(self.version_info) @@ -424,7 +426,7 @@ def check_for_version(self): albow.alert(_(' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.').format(new_version["asset"]["name"])) @classmethod - def main(self): + def main(cls): displayContext = GLDisplayContext(splash.splash) rootwidget = RootWidget(displayContext.display) @@ -441,11 +443,11 @@ def main(self): if mcedit.droppedLevel: mcedit.loadFile(mcedit.droppedLevel) - self.version_lock = threading.Lock() - self.version_info = None - self.version_checked = False + cls.version_lock = threading.Lock() + cls.version_info = None + cls.version_checked = False - fetch_version_thread = threading.Thread(target=self.fetch_version) + fetch_version_thread = threading.Thread(target=cls.fetch_version) fetch_version_thread.start() @@ -537,7 +539,7 @@ def main(self): config.version.version.set("1.1.2.0") config.save() if "-causeError" in sys.argv: - raise ValueError, "Error requested via -causeError" + raise ValueError("Error requested via -causeError") while True: try: @@ -565,7 +567,8 @@ def main(self): traceback.print_exc() mcedit.editor.handleMemoryError() - def saveWindowPosition(self): + @staticmethod + def saveWindowPosition(): """Save the window position in the configuration handler.""" if sys.platform == "win32" and config.settings.setWindowPlacement.get(): (flags, showCmd, ptMin, ptMax, rect) = mcplatform.win32gui.GetWindowPlacement( @@ -605,6 +608,7 @@ def restart(self): else: os.execl(python, python, * sys.argv) + def main(argv): """ Setup display, bundled schematics. Handle unclean @@ -642,7 +646,7 @@ def main(argv): try: display.init() - except pygame.error, e: + except pygame.error: os.environ['SDL_VIDEODRIVER'] = 'directx' try: display.init() @@ -726,6 +730,7 @@ def getSelectedMinecraftVersion(): else: return '1.8' + def getLatestMinecraftVersion(snapshots=False): import urllib2 import json @@ -735,11 +740,10 @@ def getLatestMinecraftVersion(snapshots=False): else: return versioninfo['latest']['release'] + def weird_fix(): try: from OpenGL.platform import win32 - - win32 except Exception: pass diff --git a/mceutils.py b/mceutils.py index d025e4b58..b7d090ff5 100644 --- a/mceutils.py +++ b/mceutils.py @@ -217,7 +217,7 @@ def drawCube(box, cubeType=GL.GL_QUADS, blockType=0, texture=None, textureVertic textureVertices[:] += 0.5 GL.glVertexPointer(3, GL.GL_FLOAT, 0, cubeVertices) - if texture != None: + if texture is not None: GL.glEnable(GL.GL_TEXTURE_2D) GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) @@ -231,7 +231,7 @@ def drawCube(box, cubeType=GL.GL_QUADS, blockType=0, texture=None, textureVertic GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) GL.glDisable(GL.GL_POLYGON_OFFSET_LINE) - if texture != None: + if texture is not None: GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glDisable(GL.GL_TEXTURE_2D) @@ -507,6 +507,7 @@ def setWindowCaption(prefix): prefix = _(prefix) if type(prefix) == unicode: prefix = prefix.encode("utf8") + class ctx: def __enter__(self): display.set_caption(prefix + caption) @@ -516,6 +517,7 @@ def __exit__(self, *args): return ctx() + def compareMD5Hashes(found_filters): ''' Compares the MD5 Hashes of filters @@ -526,8 +528,7 @@ def compareMD5Hashes(found_filters): ff[os.path.split(filter)[-1]] = filter try: if not os.path.exists(os.path.join(directories.getDataDir(), "filters.json")): - filterDict = {} - filterDict["filters"] = {} + filterDict = {"filters": {}} with open(os.path.join(directories.getDataDir(), "filters.json"), 'w') as j: json.dump(filterDict, j) filterInBundledFolder = directories.getAllOfAFile(os.path.join(directories.getDataDir(), "stock-filters"), ".py") @@ -545,7 +546,7 @@ def compareMD5Hashes(found_filters): bundledData = None with open(filterBundle[realName]) as bundledFilter: bundledData = bundledFilter.read() - if old_hash != hashlib.md5(bundledData).hexdigest() and bundledData != None: + if old_hash != hashlib.md5(bundledData).hexdigest() and bundledData is not None: shutil.copy(filterBundle[realName], directories.filtersDir) hashJSON["filters"][realName] = hashlib.md5(bundledData).hexdigest() if old_hash != hashlib.md5(filterData).hexdigest() and hashlib.md5(filterData).hexdigest() != hashlib.md5(bundledData).hexdigest(): @@ -559,13 +560,14 @@ def compareMD5Hashes(found_filters): data = None with open(filterBundle[bundled], 'r') as f: data = f.read() - if data != None: + if data is not None: hashJSON[bundled] = hashlib.md5(data).hexdigest() with open(os.path.join(directories.getDataDir(), "filters.json"), 'w') as done: json.dump(hashJSON, done) except Exception, e: print ('Error: {}'.format(e)) + def showProgress(progressText, progressIterator, cancel=False): """Show the progress for a long-running synchronous operation. progressIterator should be a generator-like object that can return @@ -628,7 +630,7 @@ def draw(self, surface): @property def estimateText(self): - delta = ((datetime.now() - self.startTime)) + delta = (datetime.now() - self.startTime) progressPercent = (int(self.progressFraction * 10000)) left = delta * (10000 - progressPercent) / (progressPercent or 1) return _("Time left: {0}").format(left) diff --git a/mcplatform.py b/mcplatform.py index d9bf2a868..754bff7f6 100644 --- a/mcplatform.py +++ b/mcplatform.py @@ -55,7 +55,7 @@ raise ImportError hasGtk = True except ImportError: - hasGtk = False #Using old method as fallback + hasGtk = False #Using old method as fallback texturePacksDir = os.path.join(getMinecraftProfileDirectory(getSelectedProfile()), "texturepacks") @@ -63,6 +63,7 @@ filtersDir = directories.filtersDir schematicsDir = directories.schematicsDir + def getTexturePacks(): try: return os.listdir(texturePacksDir) @@ -106,6 +107,7 @@ def getTexturePacks(): cmd_name = "Ctrl" option_name = "Alt" + def OSXVersionChecker(name,compare): """Rediculously complicated function to compare current System version to inputted version.""" if compare != 'gt' and compare != 'lt' and compare != 'eq' and compare != 'gteq' and compare != 'lteq': @@ -119,43 +121,42 @@ def OSXVersionChecker(name,compare): major, minor, patch = 10, 0, 0 - if (name.lower() == 'cheetah'): + if name.lower() == 'cheetah': minor = 0 patch = 4 - elif (name.lower() == 'puma'): + elif name.lower() == 'puma': minor = 1 patch = 5 - elif (name.lower() == 'jaguar'): + elif name.lower() == 'jaguar': minor = 2 patch = 8 - elif (name.lower() == 'panther'): + elif name.lower() == 'panther': minor = 3 patch = 9 - elif (name.lower() == 'tiger'): + elif name.lower() == 'tiger': minor = 4 patch = 11 - elif (name.lower() == 'snow_leopard'): + elif name.lower() == 'snow_leopard': minor = 5 patch = 8 - elif (name.lower() == 'snow_leopard'): + elif name.lower() == 'snow_leopard': minor = 6 patch = 8 - elif (name.lower() == 'lion'): + elif name.lower() == 'lion': minor = 7 patch = 5 - elif (name.lower() == 'mountain_lion'): + elif name.lower() == 'mountain_lion': minor = 8 patch = 5 - elif (name.lower() == 'mavericks'): + elif name.lower() == 'mavericks': minor = 9 patch = 5 - elif (name.lower() == 'yosemite'): + elif name.lower() == 'yosemite': minor = 10 patch = 0 else: major = 0 - ret_val = 0 if int(systemVersion[0]) > int(major): ret_val = 1 elif int(systemVersion[0]) < int(major): @@ -260,12 +261,13 @@ def askOpenFileWin32(title, schematics, initialDir): Title=title, Filter=f, ) - except Exception, e: + except Exception: #print "Open File: ", e pass else: return filename + def askOpenFileGtk(title, suffixes, initialDir): chooser = gtk.FileChooserDialog(title, None, gtk.FILE_CHOOSER_ACTION_SAVE, @@ -294,11 +296,12 @@ def askOpenFileGtk(title, suffixes, initialDir): filename = chooser.get_filename() else: chooser.destroy() - return # pressed cancel + return # pressed cancel chooser.destroy() return filename + def askSaveSchematic(initialDir, displayName, fileFormat): return askSaveFile(initialDir, title=_('Save this schematic...'), @@ -395,9 +398,6 @@ def askSaveFile(initialDir, title, defaultName, filetype, suffix): filename=defaultName, pathname=None) return filename - - - # if sys.platform == "win32": # try: # diff --git a/panels/options.py b/panels/options.py index 246cb80fa..0d55eeeb2 100644 --- a/panels/options.py +++ b/panels/options.py @@ -46,7 +46,6 @@ def __init__(self, mcedit): config.settings.langCode: config.settings.langCode.get() } - def initComponents(self): """Initilize the window components. Call this after translation hs been loaded.""" autoBrakeRow = mceutils.CheckBoxLabel("Autobrake", @@ -238,7 +237,8 @@ def changeLanguage(self): lng = self.langs[langName] config.settings.langCode.set(lng) - def portableButtonTooltip(self): + @staticmethod + def portableButtonTooltip(): return ( "Click to make your MCEdit install self-contained by moving the settings and schematics into the program folder", "Click to make your MCEdit install persistent by moving the settings and schematics into your Documents folder")[ diff --git a/pkgutil.py b/pkgutil.py index e474dd0e0..ce7a3c16e 100644 --- a/pkgutil.py +++ b/pkgutil.py @@ -15,6 +15,7 @@ 'ImpImporter', 'ImpLoader', 'read_code', 'extend_path', ] + def read_code(stream): # This helper is needed in order for the PEP 302 emulation to # correctly handle compiled files @@ -24,13 +25,14 @@ def read_code(stream): if magic != imp.get_magic(): return None - stream.read(4) # Skip timestamp + stream.read(4) # Skip timestamp return marshal.load(stream) def simplegeneric(func): """Make a trivial single-dispatch generic function""" registry = {} + def wrapper(*args, **kw): ob = args[0] try: @@ -251,7 +253,8 @@ def load_module(self, fullname): # normal; i.e. this is just a wrapper for standard import machinery return mod - def get_data(self, pathname): + @staticmethod + def get_data(pathname): return open(pathname, "rb").read() def _reopen(self): @@ -271,7 +274,6 @@ def _fix_name(self, fullname): return fullname def is_package(self, fullname): - fullname = self._fix_name(fullname) return self.etc[2]==imp.PKG_DIRECTORY def get_code(self, fullname=None): @@ -292,7 +294,6 @@ def get_code(self, fullname=None): return self.code def get_source(self, fullname=None): - fullname = self._fix_name(fullname) if self.source is None: mod_type = self.etc[2] if mod_type==imp.PY_SOURCE: @@ -310,13 +311,10 @@ def get_source(self, fullname=None): self.source = self._get_delegate().get_source() return self.source - def _get_delegate(self): return ImpImporter(self.filename).find_module('__init__') def get_filename(self, fullname=None): - fullname = self._fix_name(fullname) - mod_type = self.etc[2] if self.etc[2]==imp.PKG_DIRECTORY: return self._get_delegate().get_filename() elif self.etc[2] in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION): @@ -440,6 +438,7 @@ def iter_importers(fullname=""): if '.' not in fullname: yield ImpImporter() + def get_loader(module_or_name): """Get a PEP 302 "loader" object for module_or_name @@ -465,6 +464,7 @@ def get_loader(module_or_name): fullname = module_or_name return find_loader(fullname) + def find_loader(fullname): """Find a PEP 302 "loader" object for fullname @@ -519,13 +519,13 @@ def extend_path(path, name): # frozen package. Return the path unchanged in that case. return path - pname = os.path.join(*name.split('.')) # Reconstitute as relative path + pname = os.path.join(*name.split('.')) # Reconstitute as relative path # Just in case os.extsep != '.' sname = os.extsep.join(name.split('.')) sname_pkg = sname + os.extsep + "pkg" init_py = "__init__" + os.extsep + "py" - path = path[:] # Start with a copy of the existing path + path = path[:] # Start with a copy of the existing path for dir in sys.path: if not isinstance(dir, basestring) or not os.path.isdir(dir): @@ -550,11 +550,12 @@ def extend_path(path, name): line = line.rstrip('\n') if not line or line.startswith('#'): continue - path.append(line) # Don't check for existence! + path.append(line) # Don't check for existence! f.close() return path + def get_data(package, resource): """Get a resource from a package. diff --git a/png.py b/png.py index 001094bba..64f7d32a7 100644 --- a/png.py +++ b/png.py @@ -1853,7 +1853,8 @@ def iterfloat(): return x, y, iterfloat(), info - def _as_rescale(self, get, targetbitdepth): + @staticmethod + def _as_rescale(get, targetbitdepth): """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" width, height, pixels, meta = get() @@ -2302,7 +2303,6 @@ def do(): o = StringIO() testWithIO(s, o, do) r = Reader(bytes=o.getvalue()) - x, y, pixels, meta = r.read() self.assert_(r.greyscale) self.assertEqual(r.bitdepth, 2) @@ -2379,7 +2379,6 @@ def testWinfo(self): """ r = Reader(bytes=_pngsuite['basn2c16']) info = r.read()[3] - w = Writer(**info) def testPackedIter(self): """Test iterator for row when using write_packed. @@ -3404,9 +3403,9 @@ def write_pnm(file, width, height, pixels, meta): # struct format fmt = '>%d' % vpr if maxval > 0xff: - fmt = fmt + 'H' + fmt += 'H' else: - fmt = fmt + 'B' + fmt += 'B' for row in pixels: file.write(struct.pack(fmt, *row)) file.flush() diff --git a/pymclevel/block_copy.py b/pymclevel/block_copy.py index 845b279f9..629ea1f41 100644 --- a/pymclevel/block_copy.py +++ b/pymclevel/block_copy.py @@ -10,6 +10,7 @@ from entity import Entity, TileEntity from copy import deepcopy + def convertBlocks(destLevel, sourceLevel, blocks, blockData): return materials.convertBlocks(destLevel.materials, sourceLevel.materials, blocks, blockData) @@ -31,9 +32,6 @@ def unmaskedSourceMask(_sourceBlocks): def adjustCopyParameters(destLevel, sourceLevel, sourceBox, destinationPoint): - # if the destination box is outside the level, it and the source corners are moved inward to fit. - (dx, dy, dz) = map(int, destinationPoint) - log.debug(u"Asked to copy {} blocks \n\tfrom {} in {}\n\tto {} in {}".format( sourceBox.volume, sourceBox, sourceLevel, destinationPoint, destLevel)) if destLevel.Width == 0: diff --git a/pymclevel/blockrotation.py b/pymclevel/blockrotation.py index eb844b686..7b4ae6611 100644 --- a/pymclevel/blockrotation.py +++ b/pymclevel/blockrotation.py @@ -12,6 +12,7 @@ def genericRoll(cls): rotation[cls.North] = cls.Down return rotation + def genericVerticalFlip(cls): rotation = arange(16, dtype='uint8') if hasattr(cls, "Up") and hasattr(cls, "Down"): @@ -103,6 +104,7 @@ class Torch: Torch.roll[Torch.Up] = Torch.North Torch.roll[Torch.South] = Torch.Up + class Ladder: blocktypes = [alphaMaterials.Ladder.ID] @@ -142,6 +144,8 @@ class Stair: Stair.roll[Stair.TopNorth] = Stair.North # data value 0-8 bottom and 9-15 Top + + class HalfSlab: blocktypes = [b.ID for b in alphaMaterials.AllSlabs] @@ -239,6 +243,7 @@ def generic8wayRotation(cls): Rail.roll = arange(16, dtype='uint8') Rail.roll[Rail.North] = Rail.South + def applyBit(apply): def _applyBit(class_or_array): if hasattr(class_or_array, "rotateLeft"): @@ -329,6 +334,7 @@ class Lever: applyThrownBit(Lever) rotationClasses.append(Lever) + @genericFlipRotation class Button: blocktypes = [alphaMaterials.Button.ID, alphaMaterials.WoodenButton.ID] @@ -416,6 +422,7 @@ class Bed: applyBit8(Bed) applyBit4(Bed) + class EndPortal: blocktypes = [alphaMaterials.PortalFrame.ID] West = 0 @@ -427,6 +434,7 @@ class EndPortal: genericFlipRotation(EndPortal) applyBit4(EndPortal) + class Door: blocktypes = [ alphaMaterials.IronDoor.ID, @@ -480,6 +488,7 @@ class Door: rotationClasses.append(Door) + class Log: blocktypes = [ alphaMaterials.Wood.ID, @@ -558,6 +567,7 @@ class Trapdoor: applyOpenedBit = applyBit8 applyOpenedBit(Trapdoor) + class PistonBody: blocktypes = [alphaMaterials.StickyPiston.ID, alphaMaterials.Piston.ID] @@ -614,6 +624,7 @@ class HugeMushroom: HugeMushroom.roll[HugeMushroom.South] = HugeMushroom.North HugeMushroom.roll[HugeMushroom.Southwest] = HugeMushroom.Northwest + class Vines: blocktypes = [alphaMaterials.Vines.ID] @@ -675,6 +686,7 @@ class QuartzPillar: North = 3 South = 3 + @genericFlipRotation class NetherPortal: blocktypes = [alphaMaterials.NetherPortal.ID] @@ -684,6 +696,7 @@ class NetherPortal: North = 2 South = 2 + class Wood: blocktypes = [alphaMaterials.Wood.ID, alphaMaterials.Wood2.ID] @@ -766,7 +779,8 @@ class Hopper: Hopper.roll[Hopper.Down] = Hopper.South Hopper.roll[Hopper.North] = Hopper.Down -@genericFlipRotation + +@genericFlipRotation class Dropper: blocktypes = [alphaMaterials.Dropper.ID, alphaMaterials.Dispenser.ID] Down = 0 @@ -844,5 +858,6 @@ def FlipEastWest(blocks, data): def RotateLeft(blocks, data): data[:] = BlockRotation.rotateLeft[blocks, data] + def Roll(blocks, data): data[:] = BlockRotation.roll[blocks, data] \ No newline at end of file diff --git a/pymclevel/box.py b/pymclevel/box.py index 68f030794..35999b24c 100644 --- a/pymclevel/box.py +++ b/pymclevel/box.py @@ -192,7 +192,6 @@ def __contains__(self, pos): def __cmp__(self, b): return cmp((self.origin, self.size), (b.origin, b.size)) - # --- Chunk positions --- @property diff --git a/pymclevel/cachefunc.py b/pymclevel/cachefunc.py index 5b2187257..f0552f5cc 100644 --- a/pymclevel/cachefunc.py +++ b/pymclevel/cachefunc.py @@ -9,7 +9,8 @@ class Counter(dict): 'Mapping where default values are zero' - def __missing__(self, key): + @staticmethod + def __missing__(key): return 0 diff --git a/pymclevel/entity.py b/pymclevel/entity.py index cdf78aa97..3193b9330 100644 --- a/pymclevel/entity.py +++ b/pymclevel/entity.py @@ -92,7 +92,6 @@ def setpos(cls, tag, pos): for a, p in zip('xyz', pos): tag[a] = nbt.TAG_Int(p) - @classmethod def copyWithOffset(cls, tileEntity, copyOffset, staticCommands, moveSpawnerPos, first): #You'll need to use this function twice @@ -110,32 +109,32 @@ def num(x): return float(x) def coordX(x, argument): - if first == True: + if first: x = str(num(x)) + '!' + str(num(x) + copyOffset[0]) - elif argument == True and x.find("!") >= 0: + elif argument and x.find("!") >= 0: x = x[x.index("!") + 1:] x = str(num(x) + copyOffset[0]) - elif argument == False and x.find("!") >= 0: + elif not argument and x.find("!") >= 0: x = x[:x.index("!")] return x def coordY(y, argument): - if first == True: + if first: y = str(num(y)) + '!' + str(num(y) + copyOffset[1]) - elif argument == True and y.find("!") >= 0: + elif argument and y.find("!") >= 0: y = y[y.index("!") + 1:] y = str(num(y) + copyOffset[1]) - elif argument == False and y.find("!") >= 0: + elif not argument and y.find("!") >= 0: y = y[:y.index("!")] return y def coordZ(z, argument): - if first == True: + if first: z = str(num(z)) + '!' + str(num(z) + copyOffset[2]) - elif argument == True and z.find("!") >= 0: + elif argument and z.find("!") >= 0: z = z[z.index("!") + 1:] z = str(num(z) + copyOffset[2]) - elif argument == False and z.find("!") >= 0: + elif not argument and z.find("!") >= 0: z = z[:z.index("!")] return z @@ -159,7 +158,7 @@ def coords(x, y, z, argument): for mob in mobs: if "Pos" in mob: - if first == True: + if first: pos = Entity.pos(mob) x, y, z = [str(part) for part in pos] x, y, z = coords(x, y, z, moveSpawnerPos) @@ -169,7 +168,7 @@ def coords(x, y, z, argument): elif 'Temp1' in mob and 'Temp2' in mob and 'Temp3' in mob: x = mob['Temp1'] y = mob['Temp2'] - z= mob['Temp3'] + z = mob['Temp3'] del mob['Temp1'] del mob['Temp2'] del mob['Temp3'] @@ -190,13 +189,10 @@ def selectorCoords(selector): old_selector = selector try: char_num = 0 - x = "" - y = "" - z = "" new_selector = "" dont_copy = 0 if len(selector) > 4: - if selector[3] >= '0' and selector[3] <= '9': + if '0' <= selector[3] <= '9': new_selector = selector[:3] end_char_x = selector.find(',', 4, len(selector)-1) if end_char_x == -1: @@ -224,14 +220,14 @@ def selectorCoords(selector): if dont_copy != 0: dont_copy -= 1 else: - if (char != 'x' and char != 'y' and char != 'z') or letter == True: + if (char != 'x' and char != 'y' and char != 'z') or letter: new_selector += char if char == '[' or char == ',': letter = False else: letter = True - elif char == 'x' and letter == False: + elif char == 'x' and not letter: new_selector += selector[char_num:char_num + 2] char_x = char_num + 2 end_char_x = selector.find(',', char_num + 3, len(selector)-1) @@ -242,7 +238,7 @@ def selectorCoords(selector): x = coordX(x, staticCommands) new_selector += x - elif char == 'y' and letter == False: + elif char == 'y' and not letter: new_selector += selector[char_num:char_num + 2] char_y = char_num + 2 end_char_y = selector.find(',', char_num + 3, len(selector)-1) @@ -253,7 +249,7 @@ def selectorCoords(selector): y = coordY(y, staticCommands) new_selector += y - elif char == 'z' and letter == False: + elif char == 'z' and not letter: new_selector += selector[char_num:char_num + 2] char_z = char_num + 2 end_char_z = selector.find(',', char_num + 3, len(selector)-1) @@ -292,8 +288,8 @@ def selectorCoords(selector): stillExecuting = True execute = True saving_command = "" - while stillExecuting == True: - if Slash == True: + while stillExecuting: + if Slash: saving_command += '/' x, y, z = words[2:5] words[2:5] = coords(x, y, z, staticCommands) @@ -353,13 +349,13 @@ def selectorCoords(selector): z = coordZ(z, staticCommands) words[2:4] = x, z - if Slash == True: + if Slash: command = '/' else: command = "" command += ' '.join(words) - if execute == True: + if execute: command = saving_command + command eTag['Command'].value = command except: @@ -429,7 +425,7 @@ class Entity(object): "VillagerGolem": 99, "EntityHorse": 100, "Rabbit": 101, - "Villager":120, + "Villager": 120, "EnderCrystal": 200} monsters = ["Creeper", @@ -550,6 +546,7 @@ def getId(cls, v): return Entity.entityList[entity] return "No ID" + class TileTick(object): @classmethod def pos(cls, tag): diff --git a/pymclevel/gprof2dot.py b/pymclevel/gprof2dot.py index 11f8781a9..65417f49a 100644 --- a/pymclevel/gprof2dot.py +++ b/pymclevel/gprof2dot.py @@ -339,7 +339,7 @@ def integrate(self, outevent, inevent): assert call.ratio is not None # Aggregate the input for each cycle - for cycle in self.cycles: + for _ in self.cycles: total = inevent.null() for function in self.functions.itervalues(): total = inevent.aggregate(total, function[inevent]) @@ -537,7 +537,8 @@ def dump(self): for function in cycle.functions: sys.stderr.write(' Function %s\n' % (function.name,)) - def _dump_events(self, events): + @staticmethod + def _dump_events(events): for event, value in events.iteritems(): sys.stderr.write(' %s: %s\n' % (event.name, event.format(value))) @@ -1094,7 +1095,7 @@ def parse_header_line(self): self.parse_cost_line_def() or \ self.parse_cost_summary() - _detail_keys = set(('cmd', 'pid', 'thread', 'part')) + _detail_keys = {'cmd', 'pid', 'thread', 'part'} def parse_part_detail(self): return self.parse_keys(self._detail_keys) @@ -1338,7 +1339,8 @@ def add_entry(self, callers, function, callees): function_total.samples += function.samples self.update_subentries_dict(callees_total, callees) - def update_subentries_dict(self, totals, partials): + @staticmethod + def update_subentries_dict(totals, partials): for partial in partials.itervalues(): try: total = totals[partial.id] @@ -1440,7 +1442,7 @@ def parse_subentry(self): if entry.symbol.startswith('"') and entry.symbol.endswith('"'): entry.symbol = entry.symbol[1:-1] entry.id = ':'.join((entry.application, entry.image, source, entry.symbol)) - entry.self = fields.get('self', None) != None + entry.self = fields.get('self', None) is not None if entry.self: entry.id += ':self' if entry.symbol: @@ -1530,7 +1532,8 @@ def parse_value(self, tag): return value[1:-1] return value - def build_profile(self, objects, nodes): + @staticmethod + def build_profile(objects, nodes): profile = Profile() profile[SAMPLES] = 0 @@ -2031,10 +2034,12 @@ def build_call(self, fields): #call[TOTAL_TIME_RATIO] = fields['% with Children'] / 100.0 return call - def build_id(self, fields): + @staticmethod + def build_id(fields): return ':'.join([fields['Module Name'], fields['Unit Name'], fields['Routine Name']]) - def build_name(self, fields): + @staticmethod + def build_name(fields): # TODO: use more fields return fields['Routine Name'] @@ -2055,7 +2060,8 @@ def __init__(self, *filename): self.profile = Profile() self.function_ids = {} - def get_function_name(self, (filename, line, name)): + @staticmethod + def get_function_name((filename, line, name)): module = os.path.splitext(filename)[0] module = os.path.basename(module) return "%s:%d:%s" % (module, line, name) @@ -2198,7 +2204,7 @@ def hsl_to_rgb(self, h, s, l): - http://www.w3.org/TR/css3-color/#hsl-color """ - h = h % 1.0 + h %= 1.0 s = min(max(s, 0.0), 1.0) l = min(max(l, 0.0), 1.0) @@ -2218,7 +2224,8 @@ def hsl_to_rgb(self, h, s, l): return r, g, b - def _hue_to_rgb(self, m1, m2, h): + @staticmethod + def _hue_to_rgb(m1, m2, h): if h < 0.0: h += 1.0 elif h > 1.0: @@ -2389,7 +2396,8 @@ def id(self, id): raise TypeError self.write(s) - def color(self, (r, g, b)): + @staticmethod + def color((r, g, b)): def float2int(f): if f <= 0.0: @@ -2400,7 +2408,8 @@ def float2int(f): return "#" + "".join(["%02x" % float2int(c) for c in (r, g, b)]) - def escape(self, s): + @staticmethod + def escape(s): s = s.encode('utf-8') s = s.replace('\\', r'\\') s = s.replace('\n', r'\n') @@ -2566,7 +2575,8 @@ def strip_function_name(self, name): return name - def wrap_function_name(self, name): + @staticmethod + def wrap_function_name(name): """Split the function name on multiple lines.""" if len(name) > 32: diff --git a/pymclevel/indev.py b/pymclevel/indev.py index 6a939e123..19a2b638f 100644 --- a/pymclevel/indev.py +++ b/pymclevel/indev.py @@ -246,12 +246,14 @@ def rotateLeft(self): log.info(u"Rotating torches: {0}".format(len(torchIndexes.nonzero()[0]))) self.Data[torchIndexes] = torchRotation[self.Data[torchIndexes]] - def decodePos(self, v): + @staticmethod + def decodePos(v): b = 10 m = (1 << b) - 1 return v & m, (v >> b) & m, (v >> (2 * b)) - def encodePos(self, x, y, z): + @staticmethod + def encodePos(x, y, z): b = 10 return x + (y << b) + (z << (2 * b)) @@ -284,6 +286,7 @@ def saveToFile(self, filename=None): self.Entities.append(self.LocalPlayer) # fix up Entities imported from Alpha worlds + def numbersToFloats(ent): for attr in "Motion", "Pos": if attr in ent: diff --git a/pymclevel/infiniteworld.py b/pymclevel/infiniteworld.py index a1a164722..e89f317b9 100644 --- a/pymclevel/infiniteworld.py +++ b/pymclevel/infiniteworld.py @@ -240,11 +240,9 @@ def __init__(self, chunkData): self.chunkPosition = chunkData.chunkPosition self.chunkData = chunkData - def savedTagData(self): return self.chunkData.savedTagData() - def __str__(self): return u"AnvilChunk, coords:{0}, world: {1}, D:{2}, L:{3}".format(self.chunkPosition, self.world.displayName, self.dirty, self.needsLighting) @@ -293,7 +291,6 @@ def removeTileTicksInBox(self, box): self.dirty = True return super(AnvilChunk, self).removeTileTicksInBox(box) - # --- AnvilChunkData accessors --- @property @@ -540,7 +537,6 @@ def setSkylightAt(self, x, y, z, lightValue): createChunk = NotImplemented - def generateLights(self, dirtyChunkPositions=None): return exhaust(self.generateLightsIter(dirtyChunkPositions)) @@ -895,7 +891,7 @@ def __init__(self, filename): os.mkdir(filename) elif not os.path.isdir(filename): - raise IOError, "AnvilWorldFolder: Not a folder: %s" % filename + raise IOError("AnvilWorldFolder: Not a folder: %s" % filename) self.filename = filename self.regionFiles = {} @@ -939,7 +935,8 @@ def closeRegions(self): # --- Chunks and chunk listing --- - def tryLoadRegionFile(self, filepath): + @staticmethod + def tryLoadRegionFile(filepath): filename = os.path.basename(filepath) bits = filename.split('.') if len(bits) < 4 or bits[0] != 'r' or bits[3] != "mca": @@ -1084,7 +1081,7 @@ def __init__(self, filename=None, create=False, random_seed=None, last_played=No assert self.version == self.VERSION_ANVIL, "Pre-Anvil world formats are not supported (for now)" - if readonly == False: + if not readonly: if os.path.exists(self.worldFolder.getFolderPath("players")) and os.listdir( self.worldFolder.getFolderPath("players")) != []: self.playersFolder = self.worldFolder.getFolderPath("players") @@ -1096,7 +1093,6 @@ def __init__(self, filename=None, create=False, random_seed=None, last_played=No if "Player" in self.root_tag["Data"]: self.players.append("Player") - self.preloadDimensions() # --- Load, save, create --- @@ -1138,7 +1134,7 @@ def acquireSessionLock(self): def checkSessionLock(self): if self.readonly: - raise SessionLockLost, "World is opened read only." + raise SessionLockLost("World is opened read only.") lockfile = self.worldFolder.getFilePath("session.lock") try: @@ -1147,7 +1143,7 @@ def checkSessionLock(self): lock = -1 if lock != self.initTime: # I should raise an error, but this seems to always fire the exception, so I will just try to aquire it instead - raise SessionLockLost, "Session lock lost. This world is being accessed from another location." + raise SessionLockLost("Session lock lost. This world is being accessed from another location.") #self.acquireSessionLock() def loadLevelDat(self, create=False, random_seed=None, last_played=None): @@ -1173,7 +1169,7 @@ def loadLevelDat(self, create=False, random_seed=None, last_played=None): def saveInPlaceGen(self): if self.readonly: - raise IOError, "World is opened read only." + raise IOError("World is opened read only.") self.saving = True self.checkSessionLock() @@ -1206,7 +1202,7 @@ def saveInPlaceGen(self): for path, tag in self.playerTagCache.iteritems(): tag.save(path) - if not self.playersFolder is None: + if self.playersFolder is not None: for file_ in os.listdir(self.playersFolder): if file_.endswith(".dat") and file_[:-4] not in self.players: os.remove(os.path.join(self.playersFolder, file_)) @@ -1352,7 +1348,6 @@ def save_player_data(self, player_data): if p != "Player": player_data[p].save(os.path.join(self.worldFolder.getFolderPath("playerdata"), p+".dat")) - @property def bounds(self): if self._bounds is None: @@ -1444,7 +1439,7 @@ def dirhash(self, n): def _dirhash(self): n = self - n = n % 64 + n %= 64 s = u"" if n >= 36: s += u"1" @@ -1497,7 +1492,7 @@ def copyChunkFrom(self, world, cx, cz): """ assert isinstance(world, MCInfdevOldLevel) if self.readonly: - raise IOError, "World is opened read only." + raise IOError("World is opened read only.") if world.saving | self.saving: raise ChunkAccessDenied self.checkSessionLock() @@ -1549,7 +1544,8 @@ def _getChunkBytes(self, cx, cz): def _getChunkData(self, cx, cz): chunkData = self._loadedChunkData.get((cx, cz)) - if chunkData is not None: return chunkData + if chunkData is not None: + return chunkData if self.saving: raise ChunkAccessDenied @@ -1561,7 +1557,7 @@ def _getChunkData(self, cx, cz): except (MemoryError, ChunkNotPresent): raise except Exception, e: - raise ChunkMalformed, "Chunk {0} had an error: {1!r}".format((cx, cz), e), sys.exc_info()[2] + raise ChunkMalformed("Chunk {0} had an error: {1!r}".format((cx, cz), e), sys.exc_info()[2]) if not self.readonly and self.unsavedWorkFolder.containsChunk(cx, cz): chunkData.dirty = True @@ -1660,7 +1656,7 @@ def tileEntityAt(self, x, y, z): def addTileEntity(self, tileEntityTag): assert isinstance(tileEntityTag, nbt.TAG_Compound) - if not 'x' in tileEntityTag: + if 'x' not in tileEntityTag: return x, y, z = TileEntity.pos(tileEntityTag) @@ -1675,7 +1671,7 @@ def addTileEntity(self, tileEntityTag): def addTileTick(self, tickTag): assert isinstance(tickTag, nbt.TAG_Compound) - if not 'x' in tickTag: + if 'x' not in tickTag: return x, y, z = TileTick.pos(tickTag) try: @@ -1776,7 +1772,6 @@ def deleteChunk(self, cx, cz): self._bounds = None - def deleteChunksInBox(self, box): log.info(u"Deleting {0} chunks in {1}".format((box.maxcx - box.mincx) * (box.maxcz - box.mincz), ((box.mincx, box.mincz), (box.maxcx, box.maxcz)))) @@ -1884,7 +1879,7 @@ def setPlayerAbilities(self, gametype, player="Player"): # Check for the Abilities tag. It will be missing in worlds from before # Beta 1.9 Prerelease 5. - if not 'abilities' in playerTag: + if 'abilities' not in playerTag: playerTag['abilities'] = nbt.TAG_Compound() # Assumes creative (1) is the only mode with these abilities set, diff --git a/pymclevel/items.py b/pymclevel/items.py index e4c5f250b..e076fa4b0 100644 --- a/pymclevel/items.py +++ b/pymclevel/items.py @@ -56,7 +56,6 @@ def __init__(self, filename=None): self.items.update(itempacknew) except: pass - def findItem(self, id=0, damage=None): try: @@ -69,7 +68,7 @@ def findItem(self, id=0, damage=None): else: if type(item["name"][damage]) == str or type(item["name"][damage]) == unicode: return ItemType(id, item["name"][damage], item["maxdamage"], damage, item["stacksize"]) - else: + else: raise ItemNotFound() else: raise ItemNotFound() @@ -82,6 +81,7 @@ def findItemID(self, id): return self.items[item] raise ItemNotFound() + class ItemNotFound(KeyError): pass diff --git a/pymclevel/javalevel.py b/pymclevel/javalevel.py index 74d528eea..2dd78badf 100644 --- a/pymclevel/javalevel.py +++ b/pymclevel/javalevel.py @@ -36,7 +36,8 @@ def Length(self): def Width(self): return self.Blocks.shape[0] - def guessSize(self, data): + @staticmethod + def guessSize(data): Width = 64 Length = 64 Height = 64 @@ -122,7 +123,7 @@ def saveInPlaceGen(self): try: os.rename(self.filename, self.filename + ".old") - except Exception, e: + except Exception: pass try: @@ -138,7 +139,7 @@ def saveInPlaceGen(self): try: os.remove(self.filename + ".old") - except Exception, e: + except Exception: pass yield diff --git a/pymclevel/level.py b/pymclevel/level.py index 3e39ad58b..4a62c1aae 100644 --- a/pymclevel/level.py +++ b/pymclevel/level.py @@ -488,7 +488,7 @@ def removeTileEntities(self, func): return entsRemoved def removeTileEntitiesInBox(self, box): - return self.removeTileEntities(lambda p:p in box) + return self.removeTileEntities(lambda p: p in box) def removeTileTicks(self, func): if not hasattr(self, "TileTicks"): @@ -592,7 +592,6 @@ def bounds(self): cx, cz = self.chunkPosition return BoundingBox((cx << 4, 0, cz << 4), self.size) - def chunkChanged(self, needsLighting=True): self.dirty = True self.needsLighting = needsLighting or self.needsLighting @@ -601,7 +600,6 @@ def chunkChanged(self, needsLighting=True): def materials(self): return self.world.materials - def getChunkSlicesForBox(self, box): """ Given a BoundingBox enclosing part of the world, return a smaller box enclosing the part of this chunk diff --git a/pymclevel/leveldb.py b/pymclevel/leveldb.py index 96cc21131..5720fe3b7 100644 --- a/pymclevel/leveldb.py +++ b/pymclevel/leveldb.py @@ -439,7 +439,8 @@ def close(self): if self._allow_close: self._impl.close() - def newBatch(self): + @staticmethod + def newBatch(): return _OpaqueWriteBatch() def put(self, key, val, sync=None): diff --git a/pymclevel/materials.py b/pymclevel/materials.py index 4a7484811..ce4edf588 100644 --- a/pymclevel/materials.py +++ b/pymclevel/materials.py @@ -70,8 +70,8 @@ def __init__(self, defaultName="Unused Block"): self.blockTextures = zeros((id_limit, 16, 6, 2), dtype='uint16') # Sets the array size for terrain.png self.blockTextures[:] = self.defaultTexture - self.names = [[defaultName] * 16 for i in range(id_limit)] - self.aka = [[""] * 16 for i in range(id_limit)] + self.names = [[defaultName] * 16 for _ in range(id_limit)] + self.aka = [[""] * 16 for _ in range(id_limit)] self.type = [["NORMAL"] * 16] * id_limit self.blocksByType = defaultdict(list) @@ -157,8 +157,8 @@ def blocksMatching(self, name): for v2 in nameParts: Start = True j = 0 - while j < len(spiltNames) and Start == True: - if spiltNames[j] in v2 and not j in spiltNamesUsed: + while j < len(spiltNames) and Start: + if spiltNames[j] in v2 and j not in spiltNamesUsed: i += 1 spiltNamesUsed.append(j) Start = False @@ -216,7 +216,7 @@ def addYamlBlock(self, kw): # xxx unused_yaml_properties variable unused; needed for # documentation purpose of some sort? -zothar - #unused_yaml_properties = \ + # unused_yaml_properties = \ #['explored', # # 'id', # # 'idStr', @@ -996,43 +996,77 @@ def convertBlocks(destMats, sourceMats, blocks, blockData): namedMaterials = dict((i.name, i) for i in allMaterials) block_map = { - 0:"minecraft:air",1:"minecraft:stone",2:"minecraft:grass",3:"minecraft:dirt",4:"minecraft:cobblestone",5:"minecraft:planks",6:"minecraft:sapling", - 7:"minecraft:bedrock",8:"minecraft:flowing_water",9:"minecraft:water",10:"minecraft:flowing_lava",11:"minecraft:lava",12:"minecraft:sand",13:"minecraft:gravel", - 14:"minecraft:gold_ore",15:"minecraft:iron_ore",16:"minecraft:coal_ore",17:"minecraft:log",18:"minecraft:leaves",19:"minecraft:sponge",20:"minecraft:glass", - 21:"minecraft:lapis_ore",22:"minecraft:lapis_block",23:"minecraft:dispenser",24:"minecraft:sandstone",25:"minecraft:noteblock",26:"minecraft:bed", - 27:"minecraft:golden_rail",28:"minecraft:detector_rail",29:"minecraft:sticky_piston",30:"minecraft:web",31:"minecraft:tallgrass",32:"minecraft:deadbush", - 33:"minecraft:piston",34:"minecraft:piston_head",35:"minecraft:wool",36:"minecraft:piston_extension",37:"minecraft:yellow_flower",38:"minecraft:red_flower", - 39:"minecraft:brown_mushroom",40:"minecraft:red_mushroom",41:"minecraft:gold_block",42:"minecraft:iron_block",43:"minecraft:double_stone_slab", - 44:"minecraft:stone_slab",45:"minecraft:brick_block",46:"minecraft:tnt",47:"minecraft:bookshelf",48:"minecraft:mossy_cobblestone",49:"minecraft:obsidian", - 50:"minecraft:torch",51:"minecraft:fire",52:"minecraft:mob_spawner",53:"minecraft:oak_stairs",54:"minecraft:chest",55:"minecraft:redstone_wire", - 56:"minecraft:diamond_ore",57:"minecraft:diamond_block",58:"minecraft:crafting_table",59:"minecraft:wheat",60:"minecraft:farmland",61:"minecraft:furnace", - 62:"minecraft:lit_furnace",63:"minecraft:standing_sign",64:"minecraft:wooden_door",65:"minecraft:ladder",66:"minecraft:rail",67:"minecraft:stone_stairs", - 68:"minecraft:wall_sign",69:"minecraft:lever",70:"minecraft:stone_pressure_plate",71:"minecraft:iron_door",72:"minecraft:wooden_pressure_plate", - 73:"minecraft:redstone_ore",74:"minecraft:lit_redstone_ore",75:"minecraft:unlit_redstone_torch",76:"minecraft:redstone_torch",77:"minecraft:stone_button", - 78:"minecraft:snow_layer",79:"minecraft:ice",80:"minecraft:snow",81:"minecraft:cactus",82:"minecraft:clay",83:"minecraft:reeds",84:"minecraft:jukebox", - 85:"minecraft:fence",86:"minecraft:pumpkin",87:"minecraft:netherrack",88:"minecraft:soul_sand",89:"minecraft:glowstone",90:"minecraft:portal", - 91:"minecraft:lit_pumpkin",92:"minecraft:cake",93:"minecraft:unpowered_repeater",94:"minecraft:powered_repeater", - 95:"minecraft:stained_glass",96:"minecraft:trapdoor",97:"minecraft:monster_egg",98:"minecraft:stonebrick", - 99:"minecraft:brown_mushroom_block",100:"minecraft:red_mushroom_block",101:"minecraft:iron_bars",102:"minecraft:glass_pane",103:"minecraft:melon_block", - 104:"minecraft:pumpkin_stem",105:"minecraft:melon_stem",106:"minecraft:vine",107:"minecraft:fence_gate",108:"minecraft:brick_stairs",109:"minecraft:stone_brick_stairs", - 110:"minecraft:mycelium",111:"minecraft:waterlily",112:"minecraft:nether_brick",113:"minecraft:nether_brick_fence",114:"minecraft:nether_brick_stairs", - 115:"minecraft:nether_wart",116:"minecraft:enchanting_table",117:"minecraft:brewing_stand",118:"minecraft:cauldron",119:"minecraft:end_portal", - 120:"minecraft:end_portal_frame",121:"minecraft:end_stone",122:"minecraft:dragon_egg",123:"minecraft:redstone_lamp",124:"minecraft:lit_redstone_lamp", - 125:"minecraft:double_wooden_slab",126:"minecraft:wooden_slab",127:"minecraft:cocoa",128:"minecraft:sandstone_stairs",129:"minecraft:emerald_ore", - 130:"minecraft:ender_chest",131:"minecraft:tripwire_hook",132:"minecraft:tripwire",133:"minecraft:emerald_block",134:"minecraft:spruce_stairs", - 135:"minecraft:birch_stairs",136:"minecraft:jungle_stairs",137:"minecraft:command_block",138:"minecraft:beacon",139:"minecraft:cobblestone_wall", - 140:"minecraft:flower_pot",141:"minecraft:carrots",142:"minecraft:potatoes",143:"minecraft:wooden_button",144:"minecraft:skull",145:"minecraft:anvil", - 146:"minecraft:trapped_chest",147:"minecraft:light_weighted_pressure_plate",148:"minecraft:heavy_weighted_pressure_plate",149:"minecraft:unpowered_comparator", - 150:"minecraft:powered_comparator",151:"minecraft:daylight_detector",152:"minecraft:redstone_block",153:"minecraft:quartz_ore",154:"minecraft:hopper", - 155:"minecraft:quartz_block",156:"minecraft:quartz_stairs",157:"minecraft:activator_rail",158:"minecraft:dropper",159:"minecraft:stained_hardened_clay", - 160:"minecraft:stained_glass_pane",162:"minecraft:log2",163:"minecraft:acacia_stairs",164:"minecraft:dark_oak_stairs",165:"minecraft:slime",166:"minecraft:barrier", - 167:"minecraft:iron_trapdoor",168:"minecraft:prismarine",169:"minecraft:sea_lantern", - 170:"minecraft:hay_block",171:"minecraft:carpet",172:"minecraft:hardened_clay",173:"minecraft:coal_block",174:"minecraft:packed_ice",175:"minecraft:double_plant", - 176:"minecraft:standing_banner",177:"minecraft:wall_banner",178:"minecraft:daylight_detector_inverted",179:"minecraft:red_sandstone",180:"minecraft:red_sandstone_stairs", - 181:"minecraft:double_stone_slab2",182:"minecraft:stone_slab2",183:"minecraft:spruce_fence_gate",184:"minecraft:birch_fence_gate",185:"minecraft:jungle_fence_gate", - 161:"minecraft:leaves2",186:"minecraft:dark_oak_fence_gate",187:"minecraft:acacia_fence_gate",188:"minecraft:spruce_fence",189:"minecraft:birch_fence",190:"minecraft:jungle_fence", - 191:"minecraft:dark_oak_fence",192:"minecraft:acacia_fence",193:"minecraft:spruce_door",194:"minecraft:birch_door",195:"minecraft:jungle_door",196:"minecraft:acacia_door", - 197:"minecraft:dark_oak_door" + 0: "minecraft:air", 1: "minecraft:stone", 2: "minecraft:grass", 3: "minecraft:dirt", 4: "minecraft:cobblestone", + 5: "minecraft:planks", 6: "minecraft:sapling", + 7: "minecraft:bedrock", 8: "minecraft:flowing_water", 9: "minecraft:water", 10: "minecraft:flowing_lava", + 11: "minecraft:lava", 12: "minecraft:sand", 13: "minecraft:gravel", + 14: "minecraft:gold_ore", 15: "minecraft:iron_ore", 16: "minecraft:coal_ore", 17: "minecraft:log", + 18: "minecraft:leaves", 19: "minecraft:sponge", 20: "minecraft:glass", + 21: "minecraft:lapis_ore", 22: "minecraft:lapis_block", 23: "minecraft:dispenser", 24: "minecraft:sandstone", + 25: "minecraft:noteblock", 26: "minecraft:bed", + 27: "minecraft:golden_rail", 28: "minecraft:detector_rail", 29: "minecraft:sticky_piston", 30: "minecraft:web", + 31: "minecraft:tallgrass", 32: "minecraft:deadbush", + 33: "minecraft:piston", 34: "minecraft:piston_head", 35: "minecraft:wool", 36: "minecraft:piston_extension", + 37: "minecraft:yellow_flower", 38: "minecraft:red_flower", + 39: "minecraft:brown_mushroom", 40: "minecraft:red_mushroom", 41: "minecraft:gold_block", + 42: "minecraft:iron_block", 43: "minecraft:double_stone_slab", + 44: "minecraft:stone_slab", 45: "minecraft:brick_block", 46: "minecraft:tnt", 47: "minecraft:bookshelf", + 48: "minecraft:mossy_cobblestone", 49: "minecraft:obsidian", + 50: "minecraft:torch", 51: "minecraft:fire", 52: "minecraft:mob_spawner", 53: "minecraft:oak_stairs", + 54: "minecraft:chest", 55: "minecraft:redstone_wire", + 56: "minecraft:diamond_ore", 57: "minecraft:diamond_block", 58: "minecraft:crafting_table", 59: "minecraft:wheat", + 60: "minecraft:farmland", 61: "minecraft:furnace", + 62: "minecraft:lit_furnace", 63: "minecraft:standing_sign", 64: "minecraft:wooden_door", 65: "minecraft:ladder", + 66: "minecraft:rail", 67: "minecraft:stone_stairs", + 68: "minecraft:wall_sign", 69: "minecraft:lever", 70: "minecraft:stone_pressure_plate", 71: "minecraft:iron_door", + 72: "minecraft:wooden_pressure_plate", + 73: "minecraft:redstone_ore", 74: "minecraft:lit_redstone_ore", 75: "minecraft:unlit_redstone_torch", + 76: "minecraft:redstone_torch", 77: "minecraft:stone_button", + 78: "minecraft:snow_layer", 79: "minecraft:ice", 80: "minecraft:snow", 81: "minecraft:cactus", 82: "minecraft:clay", + 83: "minecraft:reeds", 84: "minecraft:jukebox", + 85: "minecraft:fence", 86: "minecraft:pumpkin", 87: "minecraft:netherrack", 88: "minecraft:soul_sand", + 89: "minecraft:glowstone", 90: "minecraft:portal", + 91: "minecraft:lit_pumpkin", 92: "minecraft:cake", 93: "minecraft:unpowered_repeater", + 94: "minecraft:powered_repeater", + 95: "minecraft:stained_glass", 96: "minecraft:trapdoor", 97: "minecraft:monster_egg", 98: "minecraft:stonebrick", + 99: "minecraft:brown_mushroom_block", 100: "minecraft:red_mushroom_block", 101: "minecraft:iron_bars", + 102: "minecraft:glass_pane", 103: "minecraft:melon_block", + 104: "minecraft:pumpkin_stem", 105: "minecraft:melon_stem", 106: "minecraft:vine", 107: "minecraft:fence_gate", + 108: "minecraft:brick_stairs", 109: "minecraft:stone_brick_stairs", + 110: "minecraft:mycelium", 111: "minecraft:waterlily", 112: "minecraft:nether_brick", + 113: "minecraft:nether_brick_fence", 114: "minecraft:nether_brick_stairs", + 115: "minecraft:nether_wart", 116: "minecraft:enchanting_table", 117: "minecraft:brewing_stand", + 118: "minecraft:cauldron", 119: "minecraft:end_portal", + 120: "minecraft:end_portal_frame", 121: "minecraft:end_stone", 122: "minecraft:dragon_egg", + 123: "minecraft:redstone_lamp", 124: "minecraft:lit_redstone_lamp", + 125: "minecraft:double_wooden_slab", 126: "minecraft:wooden_slab", 127: "minecraft:cocoa", + 128: "minecraft:sandstone_stairs", 129: "minecraft:emerald_ore", + 130: "minecraft:ender_chest", 131: "minecraft:tripwire_hook", 132: "minecraft:tripwire", + 133: "minecraft:emerald_block", 134: "minecraft:spruce_stairs", + 135: "minecraft:birch_stairs", 136: "minecraft:jungle_stairs", 137: "minecraft:command_block", + 138: "minecraft:beacon", 139: "minecraft:cobblestone_wall", + 140: "minecraft:flower_pot", 141: "minecraft:carrots", 142: "minecraft:potatoes", 143: "minecraft:wooden_button", + 144: "minecraft:skull", 145: "minecraft:anvil", + 146: "minecraft:trapped_chest", 147: "minecraft:light_weighted_pressure_plate", + 148: "minecraft:heavy_weighted_pressure_plate", 149: "minecraft:unpowered_comparator", + 150: "minecraft:powered_comparator", 151: "minecraft:daylight_detector", 152: "minecraft:redstone_block", + 153: "minecraft:quartz_ore", 154: "minecraft:hopper", + 155: "minecraft:quartz_block", 156: "minecraft:quartz_stairs", 157: "minecraft:activator_rail", + 158: "minecraft:dropper", 159: "minecraft:stained_hardened_clay", + 160: "minecraft:stained_glass_pane", 162: "minecraft:log2", 163: "minecraft:acacia_stairs", + 164: "minecraft:dark_oak_stairs", 165: "minecraft:slime", 166: "minecraft:barrier", + 167: "minecraft:iron_trapdoor", 168: "minecraft:prismarine", 169: "minecraft:sea_lantern", + 170: "minecraft:hay_block", 171: "minecraft:carpet", 172: "minecraft:hardened_clay", 173: "minecraft:coal_block", + 174: "minecraft:packed_ice", 175: "minecraft:double_plant", + 176: "minecraft:standing_banner", 177: "minecraft:wall_banner", 178: "minecraft:daylight_detector_inverted", + 179: "minecraft:red_sandstone", 180: "minecraft:red_sandstone_stairs", + 181: "minecraft:double_stone_slab2", 182: "minecraft:stone_slab2", 183: "minecraft:spruce_fence_gate", + 184: "minecraft:birch_fence_gate", 185: "minecraft:jungle_fence_gate", + 161: "minecraft:leaves2", 186: "minecraft:dark_oak_fence_gate", 187: "minecraft:acacia_fence_gate", + 188: "minecraft:spruce_fence", 189: "minecraft:birch_fence", 190: "minecraft:jungle_fence", + 191: "minecraft:dark_oak_fence", 192: "minecraft:acacia_fence", 193: "minecraft:spruce_door", + 194: "minecraft:birch_door", 195: "minecraft:jungle_door", 196: "minecraft:acacia_door", + 197: "minecraft:dark_oak_door" } __all__ = "indevMaterials, pocketMaterials, alphaMaterials, classicMaterials, namedMaterials, MCMaterials".split(", ") diff --git a/pymclevel/mclevelbase.py b/pymclevel/mclevelbase.py index 5af4c16ab..d71d8708a 100644 --- a/pymclevel/mclevelbase.py +++ b/pymclevel/mclevelbase.py @@ -42,6 +42,7 @@ class ChunkAccessDenied(ChunkNotPresent): saving is taking place""" pass + def exhaust(_iter): """Functions named ending in "Iter" return an iterable object that does long-running work and yields progress information on each call. exhaust() diff --git a/pymclevel/minecraft_server.py b/pymclevel/minecraft_server.py index 6112346e2..d24d75739 100644 --- a/pymclevel/minecraft_server.py +++ b/pymclevel/minecraft_server.py @@ -24,6 +24,8 @@ # Thank you, Stackoverflow # http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python + + def which(program): def is_exe(f): return os.path.exists(f) and os.access(f, os.X_OK) @@ -57,7 +59,6 @@ def getVersions(doSnapshot): versionSite = urllib2.urlopen("http://s3.amazonaws.com/Minecraft.Download/versions/versions.json") versionSiteResponse = versionSite.read() versionJSON = json.loads(versionSiteResponse) - version = None if doSnapshot: version = versionJSON["latest"]["snapshot"] else: @@ -360,16 +361,14 @@ def tempWorldForLevel(self, level): def generateAtPosition(self, tempWorld, tempDir, cx, cz): return exhaust(self.generateAtPositionIter(tempWorld, tempDir, cx, cz)) - def addEULA(self, tempDir): - eulaLines = [] - eulaLines.append( - "#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).\n") - eulaLines.append("#Wed Jul 23 21:10:11 EDT 2014\n") - eulaLines.append("eula=true\n") + @staticmethod + def addEULA(tempDir): + eulaLines = [ + "#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).\n", + "#Wed Jul 23 21:10:11 EDT 2014\n", "eula=true\n"] with open(tempDir + "/" + "eula.txt", "w") as f: f.writelines(eulaLines) - def generateAtPositionIter(self, tempWorld, tempDir, cx, cz, simulate=False): tempWorldRW = infiniteworld.MCInfdevOldLevel(tempWorld.filename) tempWorldRW.setPlayerSpawnPosition((cx * 16, 64, cz * 16)) @@ -429,10 +428,10 @@ def copyChunkAtPosition(self, tempWorld, level, cx, cz): try: tempChunkBytes = tempWorld._getChunkBytes(cx, cz) except ChunkNotPresent, e: - raise ChunkNotPresent, "While generating a world in {0} using server {1} ({2!r})".format(tempWorld, + raise ChunkNotPresent("While generating a world in {0} using server {1} ({2!r})".format(tempWorld, self.serverJarFile, e), sys.exc_info()[ - 2] + 2]) level.worldFolder.saveChunk(cx, cz, tempChunkBytes) level._allChunks = None diff --git a/pymclevel/nbt.py b/pymclevel/nbt.py index 81c5e541c..6bbdf5860 100644 --- a/pymclevel/nbt.py +++ b/pymclevel/nbt.py @@ -225,7 +225,6 @@ def data_type(self, value): return decoded - @classmethod def load_from(cls, ctx): value = load_string(ctx) @@ -278,7 +277,8 @@ def data_type(self, val): self.check_value(i) return list(val) - def check_value(self, val): + @staticmethod + def check_value(val): if not isinstance(val, TAG_Value): raise TypeError("Invalid type for TAG_Compound element: %s" % val.__class__.__name__) if not val.name: @@ -412,7 +412,6 @@ def __init__(self, value=None, name="", list_type=TAG_BYTE): __slots__ = ('_name', '_value') - def __repr__(self): return "<%s name='%s' list_type=%r length=%d>" % (self.__class__.__name__, self.name, tag_classes[self.list_type], @@ -424,7 +423,6 @@ def data_type(self, val): assert all([x.tagID == self.list_type for x in val]) return list(val) - @classmethod def load_from(cls, ctx): self = cls() @@ -440,7 +438,6 @@ def load_from(cls, ctx): return self - def write_value(self, buf): buf.write(chr(self.list_type)) buf.write(TAG_Int.fmt.pack(len(self.value))) diff --git a/pymclevel/player.py b/pymclevel/player.py index d215951b6..5a18943c5 100644 --- a/pymclevel/player.py +++ b/pymclevel/player.py @@ -1,6 +1,7 @@ import nbt import version_utils + class Player: def __init__(self, playerNBTFile): diff --git a/pymclevel/pocket.py b/pymclevel/pocket.py index 51c422ee9..39761c172 100644 --- a/pymclevel/pocket.py +++ b/pymclevel/pocket.py @@ -159,7 +159,6 @@ def repair(self): # logger.info("Repair complete. Removed {0} chunks, recovered {1} chunks, net {2}".format(deleted, recovered, recovered - deleted)) # - def _readChunk(self, cx, cz): cx &= 0x1f cz &= 0x1f @@ -384,7 +383,6 @@ def __init__(self, cx, cz, data, world): self.unpackChunkData() self.shapeChunkData() - def unpackChunkData(self): for key in ('SkyLight', 'BlockLight', 'Data'): dataArray = getattr(self, key) @@ -431,9 +429,10 @@ def packData(dataArray): self.DirtyColumns.tostring(), ]) + class NewPocketWorld(): @classmethod - def _isLevel(self, filename): + def _isLevel(cls, filename): clp = ("db", "level.dat") if not os.path.isdir(filename): diff --git a/pymclevel/regionfile.py b/pymclevel/regionfile.py index 8f0bd2fda..271ffe124 100644 --- a/pymclevel/regionfile.py +++ b/pymclevel/regionfile.py @@ -173,7 +173,6 @@ def repair(self): log.info("Repair complete. Removed {0} chunks, recovered {1} chunks, net {2}".format(deleted, recovered, recovered - deleted)) - def _readChunk(self, cx, cz): cx &= 0x1f cz &= 0x1f diff --git a/pymclevel/schematic.py b/pymclevel/schematic.py index d0d422b38..ede50093d 100644 --- a/pymclevel/schematic.py +++ b/pymclevel/schematic.py @@ -122,7 +122,6 @@ def __init__(self, shape=None, root_tag=None, filename=None, mats='Alpha'): self.root_tag["Data"].value &= 0xF # discard high bits - def saveToFile(self, filename=None): """ save to file named filename, or use self.filename. XXX NOT THREAD SAFE AT ALL. """ if filename is None: @@ -159,7 +158,6 @@ def saveToFile(self, filename=None): del self.root_tag["Blocks"] self.root_tag.pop("AddBlocks", None) - def __str__(self): return u"MCSchematic(shape={0}, materials={2}, filename=\"{1}\")".format(self.size, self.filename or u"", self.Materials) @@ -277,7 +275,7 @@ def rotateLeft(self): facing.value = (facing.value - 1) % 4 for tileEntity in self.TileEntities: - if not 'x' in tileEntity: + if 'x' not in tileEntity: continue newX = tileEntity["z"].value @@ -346,6 +344,7 @@ def roll(self): newY = tileTick["x"].value tileTick["x"].value = newX tileTick["y"].value = newY + def flipVerticalBlocks(self): blockrotation.FlipVertical(self.Blocks, self.Data) @@ -396,6 +395,7 @@ def flipVertical(self): 'Pointer': 4, 'Pigscene': 4, 'BurningSkull': 4} + def flipNorthSouthBlocks(self): blockrotation.FlipNorthSouth(self.Blocks, self.Data) @@ -450,7 +450,7 @@ def flipNorthSouth(self): entity["TileX"].value = self.Width - entity["TileX"].value - 1 facing.value = northSouthPaintingMap[facing.value] for tileEntity in self.TileEntities: - if not 'x' in tileEntity: + if 'x' not in tileEntity: continue tileEntity["x"].value = self.Width - tileEntity["x"].value - 1 @@ -554,7 +554,6 @@ def chestWithItemID(cls, itemID, count=64, damage=0): return chest - def getChunk(self, cx, cz): chunk = super(MCSchematic, self).getChunk(cx, cz) if "Biomes" in self.root_tag: diff --git a/pymclevel/test/nbt_test.py b/pymclevel/test/nbt_test.py index e805f261d..e6857b253 100644 --- a/pymclevel/test/nbt_test.py +++ b/pymclevel/test/nbt_test.py @@ -11,7 +11,8 @@ class TestNBT(): - def testLoad(self): + @staticmethod + def testLoad(): "Load an indev level." level = nbt.load("testfiles/hell.mclevel") @@ -26,13 +27,16 @@ def testLoad(self): return level - def testLoadUncompressed(self): + @staticmethod + def testLoadUncompressed(): root_tag = nbt.load("testfiles/uncompressed.nbt") - def testLoadNBTExplorer(self): + @staticmethod + def testLoadNBTExplorer(): root_tag = nbt.load("testfiles/modified_by_nbtexplorer.dat") - def testCreate(self): + @staticmethod + def testCreate(): "Create an indev level." # The root of an NBT file is always a TAG_Compound. @@ -125,7 +129,8 @@ def testModify(self): level["Entities"][0] = nbt.TAG_Compound([nbt.TAG_String("Creeper", "id"), nbt.TAG_List([nbt.TAG_Double(d) for d in (1, 1, 1)], "Pos")]) - def testMultipleCompound(self): + @staticmethod + def testMultipleCompound(): """ According to rumor, some TAG_Compounds store several tags with the same name. Once I find a chunk file with such a compound, I need to test TAG_Compound.get_all()""" @@ -139,8 +144,8 @@ def testSave(self): # Save the entire TAG structure to a different file. TempLevel("atlantis.mclevel", createFunc=level.save) # xxx don't use templevel here - - def testList(self): + @staticmethod + def testList(): tag = nbt.TAG_List() tag.append(nbt.TAG_Int(258)) del tag[0] @@ -171,7 +176,8 @@ def testErrors(self): else: assert False - def testSpeed(self): + @staticmethod + def testSpeed(): d = join("testfiles", "TileTicks_chunks") files = [join(d, f) for f in os.listdir(d)] startTime = time.time() diff --git a/pymclevel/test/session_lock_test.py b/pymclevel/test/session_lock_test.py index 9e9677b32..9282dcd7e 100644 --- a/pymclevel/test/session_lock_test.py +++ b/pymclevel/test/session_lock_test.py @@ -7,7 +7,6 @@ class SessionLockTest(unittest.TestCase): def test_session_lock(self): temp = TempLevel("AnvilWorld") level = temp.level - level2 = MCInfdevOldLevel(level.filename) def touch(): level.saveInPlace() diff --git a/pymclevel/test/time_nbt.py b/pymclevel/test/time_nbt.py index f8d19442d..449e37c57 100644 --- a/pymclevel/test/time_nbt.py +++ b/pymclevel/test/time_nbt.py @@ -12,6 +12,7 @@ test_file = None resaved_test_file = None + def load_file(): global test_file test_file = nbt.load(buf=test_data) @@ -19,10 +20,9 @@ def load_file(): def save_file(): global resaved_test_file - s = StringIO() resaved_test_file = test_file.save(compressed=False) # resaved_test_file = test_file.save(buf=s) - #resaved_test_file = s.getvalue() + # resaved_test_file = s.getvalue() print "File: ", path diff --git a/pymclevel/test/time_relight.py b/pymclevel/test/time_relight.py index c1e4a8e8e..3e4f79438 100644 --- a/pymclevel/test/time_relight.py +++ b/pymclevel/test/time_relight.py @@ -7,6 +7,7 @@ # import logging #logging.basicConfig(level=logging.INFO) + def natural_relight(): world = mclevel.fromFile("testfiles/AnvilWorld") t = timeit(lambda: world.generateLights(world.allChunks), number=1) diff --git a/pymclevel/test_leveldb.py b/pymclevel/test_leveldb.py index ba85bf65b..0f280bff8 100644 --- a/pymclevel/test_leveldb.py +++ b/pymclevel/test_leveldb.py @@ -290,7 +290,7 @@ def testOpaqueWriteBatch(self): def testKeysWithZeroBytes(self): db = self.db_class(self.db_path, create_if_missing=True) - key_with_zero_byte = ("\x01\x00\x02\x03\x04") + key_with_zero_byte = "\x01\x00\x02\x03\x04" db.put(key_with_zero_byte, "hey") self.assertEqual(db.get(key_with_zero_byte), "hey") it = db.iterator().seekFirst() @@ -302,7 +302,7 @@ def testKeysWithZeroBytes(self): def testValuesWithZeroBytes(self): db = self.db_class(self.db_path, create_if_missing=True) - value_with_zero_byte = ("\x01\x00\x02\x03\x04") + value_with_zero_byte = "\x01\x00\x02\x03\x04" db.put("hey", value_with_zero_byte) self.assertEqual(db.get("hey"), value_with_zero_byte) it = db.iterator().seekFirst() diff --git a/pyperclip.py b/pyperclip.py index 5cd2f83e7..a907fcb00 100644 --- a/pyperclip.py +++ b/pyperclip.py @@ -47,16 +47,19 @@ # * Removed Python 3 compatability # * Removed PyQT support -import platform, os +import platform +import os + def winGetClipboard(): ctypes.windll.user32.OpenClipboard(None) - pcontents = ctypes.windll.user32.GetClipboardData(1) # 1 is CF_TEXT + pcontents = ctypes.windll.user32.GetClipboardData(1) # 1 is CF_TEXT data = ctypes.c_char_p(pcontents).value #ctypes.windll.kernel32.GlobalUnlock(pcontents) ctypes.windll.user32.CloseClipboard() return data + def winSetClipboard(text): text = str(text) GMEM_DDESHARE = 0x2000 @@ -69,21 +72,25 @@ def winSetClipboard(text): ctypes.windll.user32.SetClipboardData(1, hCd) ctypes.windll.user32.CloseClipboard() + def macSetClipboard(text): text = str(text) outf = os.popen('pbcopy', 'w') outf.write(text) outf.close() + def macGetClipboard(): outf = os.popen('pbpaste', 'r') content = outf.read() outf.close() return content + def gtkGetClipboard(): return gtk.Clipboard().wait_for_text() + def gtkSetClipboard(text): global cb text = str(text) @@ -91,31 +98,37 @@ def gtkSetClipboard(text): cb.set_text(text) cb.store() + def qtGetClipboard(): return str(cb.text()) + def qtSetClipboard(text): text = str(text) cb.setText(text) + def xclipSetClipboard(text): text = str(text) outf = os.popen('xclip -selection c', 'w') outf.write(text) outf.close() + def xclipGetClipboard(): outf = os.popen('xclip -selection c -o', 'r') content = outf.read() outf.close() return content + def xselSetClipboard(text): text = str(text) outf = os.popen('xsel -i', 'w') outf.write(text) outf.close() + def xselGetClipboard(): outf = os.popen('xsel -o', 'r') content = outf.read() diff --git a/raycaster.py b/raycaster.py index b388ada4c..54c6520df 100644 --- a/raycaster.py +++ b/raycaster.py @@ -9,47 +9,48 @@ Implementation in javascript by Kevin Reid: https://gamedev.stackexchange.com/questions/47362/cast-ray-to-select-block-in-voxel-game """ + + def _rawRaycast(origin, direction): def _signum(x): - if (x > 0): + if x > 0: return 1 - elif(x < 0): + elif x < 0: return -1 else: return 0 def _intbound(s,ds): - if (ds<0): + if ds<0: return _intbound(-s,-ds) else: - s = s % 1 + s %= 1 return (1-s)/ds x,y,z = map(int,map(math.floor,origin)) dx,dy,dz = direction - if (dx == 0): #Yes, I know this is hacky. It works though. + if dx == 0: #Yes, I know this is hacky. It works though. dx = 0.000000001 - if (dy == 0): + if dy == 0: dy = 0.000000001 - if (dz == 0): + if dz == 0: dz = 0.000000001 - stepX,stepY,stepZ = map(_signum,direction) tMaxX,tMaxY,tMaxZ = map(_intbound,origin,(dx,dy,dz)) tDeltaX = stepX/dx tDeltaY = stepY/dy tDeltaZ = stepZ/dz - if (dx == 0 and dy == 0 and dz == 0): + if dx == 0 and dy == 0 and dz == 0: raise Exception('Infinite ray trace detected') face = None while True: yield ((x,y,z),face) - if (tMaxX < tMaxY): - if (tMaxX < tMaxZ): + if tMaxX < tMaxY: + if tMaxX < tMaxZ: x += stepX tMaxX += tDeltaX face = (-stepX, 0,0) @@ -58,7 +59,7 @@ def _intbound(s,ds): tMaxZ += tDeltaZ face = (0,0,-stepZ) else: - if (tMaxY < tMaxZ): + if tMaxY < tMaxZ: y += stepY tMaxY += tDeltaY face = (0,-stepY,0) @@ -75,27 +76,29 @@ def _intbound(s,ds): This method returns a (position,face) tuple pair. """ + + def firstBlock(origin, direction, level, radius, viewMode=None): if viewMode == "Chunk": raise TooFarException("There are no valid blocks within range") startPos = map(int,map(math.floor,origin)) block = level.blockAt(*startPos) - callback = None tooMuch = 0 - if (block == 8 or block == 9): + if block == 8 or block == 9: callback = _WaterCallback() else: callback = _StandardCallback() for i in _rawRaycast(origin,direction): tooMuch += 1 block = level.blockAt(*i[0]) - if (callback.check(i[0],block)): + if callback.check(i[0],block): return i[0],i[1] - if (_tooFar(origin, i[0], radius) or _tooHighOrLow(i[0])): + if _tooFar(origin, i[0], radius) or _tooHighOrLow(i[0]): raise TooFarException("There are no valid blocks within range") if tooMuch >= 720: return i[0], i[1] + def _tooFar(origin, position, radius): x = abs(origin[0] - position[0]) y = abs(origin[1] - position[1]) @@ -104,6 +107,7 @@ def _tooFar(origin, position, radius): result = x>radius or y>radius or z>radius return result + def _tooHighOrLow(position): return position[1] > 255 or position[1] < 0 @@ -111,9 +115,11 @@ def _tooHighOrLow(position): class TooFarException(Exception): def __init__(self,value): self.value = value + def __str__(self): return repr(self.value) + class Callback: """ Returns true if the ray tracer is to be terminated @@ -121,17 +127,18 @@ class Callback: def check(self, position,block): pass + class _WaterCallback(Callback): def __init__(self): self.escapedBlock = False def check(self, position, block): - if (block == 8 or block == 9): + if block == 8 or block == 9: return False - elif (block == 0): + elif block == 0: self.escapedBlock = True return False - elif (self.escapedBlock and block != 0 ): + elif self.escapedBlock and block != 0: return True return True @@ -142,9 +149,9 @@ def __init__(self): def check(self, position, block): if not self.escapedBlock: - if (block == 0): + if block == 0: self.escapedBlock = True return - if (block != 0): + if block != 0: return True return False diff --git a/release.py b/release.py index 34f09ce8d..4123424e6 100644 --- a/release.py +++ b/release.py @@ -17,6 +17,7 @@ def get_version(): except: raise + def get_release_tag(): ''' Gets the stage of development MCEdit-Unified is in @@ -27,6 +28,8 @@ def get_release_tag(): return current["tag_name"] except: raise + + def is_dev(): ''' Checks if MCEdit-Unified is in development mode diff --git a/renderer.py b/renderer.py index 8fe276a7d..a7a7fc061 100644 --- a/renderer.py +++ b/renderer.py @@ -201,12 +201,11 @@ def calcFaces(self): self.blockRenderers = blockRenderers if self.renderer.chunkCalculator: - for i in self.renderer.chunkCalculator.calcFacesForChunkRenderer(self): + for _ in self.renderer.chunkCalculator.calcFacesForChunkRenderer(self): yield else: raise StopIteration - yield def vertexArraysDone(self): bufferSize = 0 @@ -325,51 +324,51 @@ def __init__(self, level): class renderstatePlain(object): @classmethod - def bind(self): + def bind(cls): pass @classmethod - def release(self): + def release(cls): pass class renderstateVines(object): @classmethod - def bind(self): + def bind(cls): GL.glDisable(GL.GL_CULL_FACE) GL.glEnable(GL.GL_ALPHA_TEST) @classmethod - def release(self): + def release(cls): GL.glEnable(GL.GL_CULL_FACE) GL.glDisable(GL.GL_ALPHA_TEST) class renderstateLowDetail(object): @classmethod - def bind(self): + def bind(cls): GL.glDisable(GL.GL_CULL_FACE) GL.glDisable(GL.GL_TEXTURE_2D) @classmethod - def release(self): + def release(cls): GL.glEnable(GL.GL_CULL_FACE) GL.glEnable(GL.GL_TEXTURE_2D) class renderstateAlphaTest(object): @classmethod - def bind(self): + def bind(cls): GL.glEnable(GL.GL_ALPHA_TEST) @classmethod - def release(self): + def release(cls): GL.glDisable(GL.GL_ALPHA_TEST) class _renderstateAlphaBlend(object): @classmethod - def bind(self): + def bind(cls): GL.glEnable(GL.GL_BLEND) @classmethod - def release(self): + def release(cls): GL.glDisable(GL.GL_BLEND) class renderstateWater(_renderstateAlphaBlend): @@ -380,14 +379,14 @@ class renderstateIce(_renderstateAlphaBlend): class renderstateEntity(object): @classmethod - def bind(self): + def bind(cls): GL.glDisable(GL.GL_DEPTH_TEST) # GL.glDisable(GL.GL_CULL_FACE) GL.glDisable(GL.GL_TEXTURE_2D) GL.glEnable(GL.GL_BLEND) @classmethod - def release(self): + def release(cls): GL.glEnable(GL.GL_DEPTH_TEST) # GL.glEnable(GL.GL_CULL_FACE) GL.glEnable(GL.GL_TEXTURE_2D) @@ -567,7 +566,8 @@ def calcFacesForChunkRenderer(self, cr): cr.vertexArraysDone() raise StopIteration - def getNeighboringChunks(self, chunk): + @staticmethod + def getNeighboringChunks(chunk): cx, cz = chunk.chunkPosition level = chunk.world @@ -587,7 +587,8 @@ def getNeighboringChunks(self, chunk): neighboringChunks[dir] = pymclevel.infiniteworld.ZeroChunk(level.Height) return neighboringChunks - def getAreaBlocks(self, chunk, neighboringChunks): + @staticmethod + def getAreaBlocks(chunk, neighboringChunks): chunkWidth, chunkLength, chunkHeight = chunk.Blocks.shape areaBlocks = numpy.zeros((chunkWidth + 2, chunkLength + 2, chunkHeight + 2), numpy.uint16) @@ -602,7 +603,8 @@ def getAreaBlocks(self, chunk, neighboringChunks): :chunkHeight] return areaBlocks - def getFacingBlockIndices(self, areaBlocks, areaBlockMats): + @staticmethod + def getFacingBlockIndices(areaBlocks, areaBlockMats): facingBlockIndices = [None] * 6 exposedFacesX = (areaBlockMats[:-1, 1:-1, 1:-1] != areaBlockMats[1:, 1:-1, 1:-1]) @@ -713,12 +715,12 @@ def calcHighDetailFaces(self, cr, facingBlockIndices = self.getFacingBlockIndices(areaBlocks, facingMats) yield - for i in self.computeGeometry(chunk, areaBlockMats, facingBlockIndices, areaBlockLights, cr, blockRenderers): + for _ in self.computeGeometry(chunk, areaBlockMats, facingBlockIndices, areaBlockLights, cr, blockRenderers): yield def computeGeometry(self, chunk, areaBlockMats, facingBlockIndices, areaBlockLights, chunkRenderer, blockRenderers): blocks, blockData = chunk.Blocks, chunk.Data - blockData = blockData & 0xf + blockData &= 0xf blockMaterials = areaBlockMats[1:-1, 1:-1, 1:-1] if self.roughGraphics: blockMaterials.clip(0, 1, blockMaterials) @@ -730,7 +732,7 @@ def computeGeometry(self, chunk, areaBlockMats, facingBlockIndices, areaBlockLig sy = slice(y, y + 16) asy = slice(y, y + 18) - for _i in self.computeCubeGeometry( + for _ in self.computeCubeGeometry( y, blockRenderers, blocks[sx, sz, sy], @@ -896,7 +898,8 @@ def drawFaceVertices(self, buf): GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) GL.glDepthMask(True) - def _computeVertices(self, positions, colors, offset=False, chunkPosition=(0, 0)): + @staticmethod + def _computeVertices(positions, colors, offset=False, chunkPosition=(0, 0)): cx, cz = chunkPosition x = cx << 4 z = cz << 4 @@ -923,7 +926,7 @@ def makeChunkVertices(self, chunk): for i, ent in enumerate(chunk.TileEntities): if i % 10 == 0: yield - if not 'x' in ent: + if 'x' not in ent: continue tilePositions.append(pymclevel.TileEntity.pos(ent)) tiles = self._computeVertices(tilePositions, (0xff, 0xff, 0x33, 0x44), chunkPosition=chunk.chunkPosition) @@ -937,7 +940,7 @@ class BaseEntityRenderer(EntityRendererGeneric): class MonsterRenderer(BaseEntityRenderer): layer = Layer.Entities # xxx Monsters - notMonsters = set(["Item", "XPOrb", "Painting"]) + notMonsters = {"Item", "XPOrb", "Painting"} def makeChunkVertices(self, chunk): monsterPositions = [] @@ -959,7 +962,8 @@ def makeChunkVertices(self, chunk): class EntityRenderer(BaseEntityRenderer): - def makeChunkVertices(self, chunk): + @staticmethod + def makeChunkVertices(chunk): yield @@ -1012,6 +1016,7 @@ def makeChunkVertices(self, chunk): chunkPosition=chunk.chunkPosition)) yield + class TerrainPopulatedRenderer(EntityRendererGeneric): layer = Layer.TerrainPopulated vertexTemplate = numpy.zeros((6, 4, 6), 'float32') @@ -1076,6 +1081,7 @@ def getpop(ch): yield + class ChunkBorderRenderer(EntityRendererGeneric): layer = Layer.ChunkBorder color = (0, 210, 225) @@ -1099,7 +1105,6 @@ def makeChunkVertices(self, chunk): self.vertexArrays.append(verts) yield - def drawFaceVertices(self, buf): if 0 == len(buf): return @@ -1122,7 +1127,6 @@ def drawFaceVertices(self, buf): GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) - class LowDetailBlockRenderer(BlockRenderer): renderstate = ChunkCalculator.renderstateLowDetail detailLevels = (1,) @@ -1670,6 +1674,7 @@ def makeRailVertices(self, facingBlockIndices, blocks, blockMaterials, blockData makeVertices = makeRailVertices + class LadderBlockRenderer(BlockRenderer): blocktypes = [pymclevel.materials.alphaMaterials.Ladder.ID] @@ -1714,6 +1719,7 @@ def ladderVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, makeVertices = ladderVertices + class WallSignBlockRenderer(BlockRenderer): blocktypes = [pymclevel.materials.alphaMaterials.WallSign.ID] @@ -1758,6 +1764,7 @@ def WallSignVertices(self, facingBlockIndices, blocks, blockMaterials, blockData makeVertices = WallSignVertices + class SnowBlockRenderer(BlockRenderer): blocktypes = [pymclevel.materials.alphaMaterials.SnowLayer.ID] @@ -1796,6 +1803,7 @@ def makeSnowVertices(self, facingBlockIndices, blocks, blockMaterials, blockData makeVertices = makeSnowVertices + class CarpetBlockRenderer(BlockRenderer): blocktypes = [pymclevel.materials.alphaMaterials.Carpet.ID, #Separate before implementing layers pymclevel.materials.alphaMaterials.Lilypad.ID] @@ -1835,6 +1843,7 @@ def makeCarpetVertices(self, facingBlockIndices, blocks, blockMaterials, blockDa makeVertices = makeCarpetVertices + class CactusBlockRenderer(BlockRenderer): blocktypes = [pymclevel.materials.alphaMaterials.Cactus.ID] @@ -1941,6 +1950,7 @@ def makePlateVertices(self, facingBlockIndices, blocks, blockMaterials, blockDat makeVertices = makePlateVertices + class EnchantingBlockRenderer( BlockRenderer): #Note: Enderportal frame side sprite has been lowered 1 pixel to use this renderer, will need separate renderer for eye. blocktypes = [pymclevel.materials.alphaMaterials.EnchantmentTable.ID, @@ -2160,11 +2170,8 @@ class FenceBlockRenderer(BlockRenderer): #This code is written to only accept o def fenceVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): fenceMask = self.getMaterialIndices(blockMaterials) fenceIndices = fenceMask.nonzero() - bdata = blockData[fenceMask] yield - tex = texMap(blocks[fenceMask], blockData[fenceMask], 0)[:, numpy.newaxis, 0:2] - vertexArray = numpy.zeros((len(fenceIndices[0]), 6, 4, 6), dtype='float32') for indicies in range(3): dimension = (0, 2, 1)[indicies] @@ -2193,7 +2200,6 @@ class NetherFenceBlockRenderer(BlockRenderer): def fenceVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, areaBlockLights, texMap): fenceMask = self.getMaterialIndices(blockMaterials) fenceIndices = fenceMask.nonzero() - fenceBlocks = blocks[fenceMask] yield vertexArray = numpy.zeros((len(fenceIndices[0]), 6, 4, 6), dtype='float32') @@ -2249,7 +2255,6 @@ def stairVertices(self, facingBlockIndices, blocks, blockMaterials, blockData, a stairTop = (stairData >> 2).astype(bool) stairData &= 3 - blockLight = areaBlockLights[1:-1, 1:-1, 1:-1] x, z, y = materialIndices.nonzero() for _ in ("slab", "step"): @@ -2414,7 +2419,7 @@ def __init__(self, level=None, alpha=1.0): self.masterLists = None - alpha = alpha * 255 + alpha *= 255 self.alpha = (int(alpha) & 0xff) self.chunkStartTime = datetime.now() @@ -2452,7 +2457,6 @@ def __init__(self, level=None, alpha=1.0): if self.level.__class__.__name__ in ("FakeLevel","MCSchematic"): self.toggleLayer(False, 'ChunkBorder') - chunkClass = ChunkRenderer calculatorClass = ChunkCalculator @@ -2589,7 +2593,6 @@ def level(self, level): self.chunkCalculator = self.calculatorClass(self.level) self.oldPosition = None - level.allChunks self.loadNearbyChunks() @@ -2666,7 +2669,6 @@ def discardChunksOutsideViewDistance(self): if not len(self.chunkRenderers): return (ox, oz) = origin - bytes = 0 # chunks = numpy.fromiter(self.chunkRenderers.iterkeys(), dtype='int32', count=len(self.chunkRenderers)) chunks = numpy.fromiter(self.chunkRenderers.iterkeys(), dtype='i,i', count=len(self.chunkRenderers)) chunks.dtype = 'int32' @@ -2843,7 +2845,8 @@ def floorTexture(self): self._floorTexture = Texture(self.makeFloorTex) return self._floorTexture - def makeFloorTex(self): + @staticmethod + def makeFloorTex(): color0 = (0xff, 0xff, 0xff, 0x22) color1 = (0xff, 0xff, 0xff, 0x44) @@ -2978,7 +2981,6 @@ def draw(self): if not self.render: return - chunksDrawn = 0 if self.level.materials.name in ("Pocket", "Alpha"): GL.glMatrixMode(GL.GL_TEXTURE) GL.glScalef(1 / 2., 1 / 2., 1 / 2.) @@ -3052,7 +3054,7 @@ def makeWorkIterator(self): if len(self.invalidChunkQueue): c = self.invalidChunkQueue[0] - for i in self.workOnChunk(c): + for _ in self.workOnChunk(c): yield self.invalidChunkQueue.popleft() @@ -3078,11 +3080,11 @@ def makeWorkIterator(self): break else: - for i in self.workOnChunk(c): + for _ in self.workOnChunk(c): yield else: - for i in self.workOnChunk(c): + for _ in self.workOnChunk(c): yield yield @@ -3107,7 +3109,7 @@ def calcFacesForChunkRenderer(self, cr): calc = cr.calcFaces() work = 0 - for i in calc: + for _ in calc: yield work += 1 @@ -3123,11 +3125,10 @@ def workOnChunk(self, c): if not self.viewingFrustum.visible1([c[0] * 16 + 8, self.level.Height / 2, c[1] * 16 + 8, 1.0], self.level.Height / 2): raise StopIteration - yield faceInfoCalculator = self.calcFacesForChunkRenderer(cr) try: - for result in faceInfoCalculator: + for _ in faceInfoCalculator: work += 1 if (work % MCRenderer.workFactor) == 0: yield @@ -3161,8 +3162,6 @@ def chunkDone(self, chunkRenderer, work): self.chunkSamples.pop(0) self.chunkSamples.append(self.chunkStartTime - self.oldChunkStartTime) - cx, cz = chunkRenderer.chunkPosition - class PreviewRenderer(MCRenderer): isPreviewer = True @@ -3199,7 +3198,6 @@ def rendermain(): from utilities.gl_display_context import GLDisplayContext from OpenGL import GLU - cxt = GLDisplayContext() import pygame # distance = 4000 diff --git a/resource_packs.py b/resource_packs.py index 66d2e41a7..5c6c65026 100644 --- a/resource_packs.py +++ b/resource_packs.py @@ -18,6 +18,7 @@ except: pass + def step(slot): texSlot = slot*16 return texSlot @@ -502,12 +503,11 @@ def step(slot): # Start Comparator Block } + class IResourcePack: def __init__(self): self.__stop = False - tpBasePath = type(os.path.join(directories.parentDir, "textures")) - tpPackName = type(self._pack_name) texture_path = os.path.join(directories.parentDir, "textures", self._pack_name) self.texture_path = texture_path self._isEmpty = False @@ -583,7 +583,7 @@ def parse_terrain_png(self): os.remove(self._pack_name.replace(" ", "_")+".png") except: pass - if self.propogated_textures == []: + if not self.propogated_textures: os.remove(self._terrain_path) self._isEmpty = True #print u"{} did not replace any textures".format(self._pack_name) @@ -614,7 +614,7 @@ def __init__(self, zipfileFile, noEncConvert=False): try: self.open_pack() except Exception, e: - print ("Error while trying to load one of the resource packs: {}").format(e) + print "Error while trying to load one of the resource packs: {}".format(e) def open_pack(self): zfile = zipfile.ZipFile(self.zipfile) @@ -659,7 +659,7 @@ def open_pack(self): if possible_texture.size == (32, 32): self.block_image[block_name] = possible_texture.resize((16, 16)) elif possible_texture.size == (64, 64) or possible_texture.size == (128, 128) or possible_texture.size == (256, 256): - self.big_textures_counted = self.big_textures_counted + 1 + self.big_textures_counted += 1 else: self.block_image[block_name] = possible_texture.crop((0,0,16,16)) if self.big_textures_counted >= self.big_textures_max: @@ -720,7 +720,7 @@ def add_textures(self): if possible_texture.size == (32, 32): self.block_image[block_name] = possible_texture.resize((16, 16)) if possible_texture.size == (64, 64) or possible_texture.size == (128, 128) or possible_texture.size == (256, 256): - self.big_textures_counted = self.big_textures_counted + 1 + self.big_textures_counted += 1 else: self.block_image[block_name] = possible_texture.crop((0,0,16,16)) if self.big_textures_counted >= self.big_textures_max: @@ -728,6 +728,7 @@ def add_textures(self): else: self.parse_terrain_png() + class DefaultResourcePack(IResourcePack): def __init__(self): @@ -781,6 +782,7 @@ def setup_resource_packs(): pass return terrains + class ResourcePackHandler: def __init__(self): diff --git a/stock-brushes/Erode.py b/stock-brushes/Erode.py index 672cb55a2..5394f2070 100644 --- a/stock-brushes/Erode.py +++ b/stock-brushes/Erode.py @@ -4,6 +4,7 @@ displayName = 'Erode' + def createInputs(self): self.inputs = ( {'Hollow': False}, @@ -14,6 +15,7 @@ def createInputs(self): {'Minimum Spacing': 1} ) + def apply(self, op, point): brushBox = op.tool.getDirtyBox(point, op.tool).expand(1) @@ -33,18 +35,17 @@ def apply(self, op, point): fillBlockID = bins.argmax() xcount = -1 - for x in blocks: + for _ in blocks: xcount += 1 ycount = -1 - for y in blocks[xcount]: + for _ in blocks[xcount]: ycount += 1 zcount = -1 - for z in blocks[xcount][ycount]: + for _ in blocks[xcount][ycount]: zcount += 1 if blocks[xcount][ycount][zcount] == fillBlockID: fillBlockData = data[xcount][ycount][zcount] - def getNeighbors(solidBlocks): neighbors = numpy.zeros(solidBlocks.shape, dtype='uint8') neighbors[1:-1, 1:-1, 1:-1] += solidBlocks[:-2, 1:-1, 1:-1] diff --git a/stock-brushes/Fill.py b/stock-brushes/Fill.py index 383744c02..612de1417 100644 --- a/stock-brushes/Fill.py +++ b/stock-brushes/Fill.py @@ -5,6 +5,7 @@ displayName = 'Fill' mainBlock = 'Block' + def createInputs(self): self.inputs = ( {'Hollow': False}, @@ -15,6 +16,7 @@ def createInputs(self): {'Minimum Spacing': 1} ) + def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) @@ -23,7 +25,7 @@ def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): airFill = op.options['Fill Air'] - if airFill == False: + if not airFill: airtable = numpy.zeros((materials.id_limit, 16), dtype='bool') airtable[0] = True replaceMaskAir = airtable[blocks, data] diff --git a/stock-brushes/Flood Fill.py b/stock-brushes/Flood Fill.py index 7038d956f..4de332b34 100644 --- a/stock-brushes/Flood Fill.py +++ b/stock-brushes/Flood Fill.py @@ -12,12 +12,14 @@ displayName = 'Flood Fill' disableStyleButton = True + def createInputs(self): self.inputs = ( {'Block': materials.blockWithID(1, 0)}, {'Indiscriminate': False}, ) + def apply(self, op, point): undoLevel = pymclevel.MCInfdevOldLevel(mkundotemp(), create=True) @@ -38,7 +40,7 @@ def saveUndoChunk(cx, cz): checkData = False if doomedBlock == 2: # grass doomedBlock = 3 # dirt - if doomedBlock == op.options['Block'].ID and (doomedBlockData == op.options['Block'].blockData or checkData == False): + if doomedBlock == op.options['Block'].ID and (doomedBlockData == op.options['Block'].blockData or not checkData): return x, y, z = point diff --git a/stock-brushes/Paste.py b/stock-brushes/Paste.py index c11864dca..1f84811e3 100644 --- a/stock-brushes/Paste.py +++ b/stock-brushes/Paste.py @@ -8,17 +8,20 @@ addPasteButton = True disableStyleButton = True + def createInputs(self): self.inputs= ( ) pass + def createDirtyBox(self, point, tool): newpoint = [] for p in point: newpoint.append(p-1) return BoundingBox(newpoint, tool.level.size) + def apply(self, op, point): level = op.tool.level newpoint = [] diff --git a/stock-brushes/Replace.py b/stock-brushes/Replace.py index e8db570a7..a4c25da31 100644 --- a/stock-brushes/Replace.py +++ b/stock-brushes/Replace.py @@ -7,6 +7,7 @@ secondaryBlock = 'Block' wildcardBlocks = ['Block'] + def createInputs(self): self.inputs = ( {'Hollow': False}, @@ -17,13 +18,13 @@ def createInputs(self): {'Minimum Spacing': 1} ) + def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) blocks = chunk.Blocks[slices] data = chunk.Data[slices] - replaceWith = op.options['Block'] if op.options['Block'].wildcard: print "Wildcard replace" blocksToReplace = [] diff --git a/stock-brushes/Topsoil.py b/stock-brushes/Topsoil.py index c9458b180..a2db32e27 100644 --- a/stock-brushes/Topsoil.py +++ b/stock-brushes/Topsoil.py @@ -4,13 +4,14 @@ displayName = "Topsoil" + def createInputs(self): self.inputs = ( {'Hollow': False}, {'Noise': 100}, {'W': (3, 1, 4096), 'H': (3, 1, 4096), 'L': (3, 1, 4096)}, {'Block': materials.blockWithID(1, 0)}, - {'Depth': (1)}, + {'Depth': 1}, {'Only Change Natural Earth': False}, {'Minimum Spacing': 1}, ) @@ -26,7 +27,6 @@ def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) - if op.options['Only Change Natural Earth']: try: # try to get the block mask from the topsoil filter diff --git a/stock-brushes/Varied Fill.py b/stock-brushes/Varied Fill.py index eb3ae65d7..8249bb789 100644 --- a/stock-brushes/Varied Fill.py +++ b/stock-brushes/Varied Fill.py @@ -8,6 +8,7 @@ mainBlock = "Block 1" secondaryBlock = "Block" + def createInputs(self): self.inputs = ( {'Hollow': False}, @@ -23,6 +24,7 @@ def createInputs(self): {'Fill Air': True}, ) + def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) @@ -45,7 +47,7 @@ def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): print "Total Chance value can't be 0." return - if airFill == False: + if not airFill: airtable = numpy.zeros((materials.id_limit, 16), dtype='bool') airtable[0] = True replaceMaskAir = airtable[blocks, data] @@ -56,17 +58,15 @@ def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMaskOption3 = numpy.copy(brushMask) brushMaskOption4 = numpy.copy(brushMask) - x=-1 - y=-1 - z=-1 + x = -1 - for array_x in brushMask: + for _ in brushMask: x += 1 y = -1 - for array_y in brushMask[x]: + for _ in brushMask[x]: y += 1 - z=-1 - for array_z in brushMask[x][y]: + z = -1 + for _ in brushMask[x][y]: z += 1 if brushMask[x][y][z]: randomChance = random.randint(1, totalChance) diff --git a/stock-brushes/Varied Replace.py b/stock-brushes/Varied Replace.py index e46710b9f..53252f66b 100644 --- a/stock-brushes/Varied Replace.py +++ b/stock-brushes/Varied Replace.py @@ -9,6 +9,7 @@ mainBlock = "Block 1" secondaryBlock = "Block" + def createInputs(self): self.inputs = ( {'Hollow': False}, @@ -24,10 +25,10 @@ def createInputs(self): {'Minimum Spacing': 1}, ) + def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) - airFill = op.options['Fill Air'] replaceWith1 = op.options['Block 1'] chanceA = op.options['Weight 1'] replaceWith2 = op.options['Block 2'] @@ -46,7 +47,6 @@ def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): blocks = chunk.Blocks[slices] data = chunk.Data[slices] - replaceWith = op.options['Block'] if op.options['Block'].wildcard: print "Wildcard replace" blocksToReplace = [] @@ -64,17 +64,15 @@ def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMaskOption3 = numpy.copy(brushMask) brushMaskOption4 = numpy.copy(brushMask) - x=-1 - y=-1 - z=-1 + x = -1 - for array_x in brushMask: + for _ in brushMask: x += 1 y = -1 - for array_y in brushMask[x]: + for _ in brushMask[x]: y += 1 - z=-1 - for array_z in brushMask[x][y]: + z = -1 + for _ in brushMask[x][y]: z += 1 if brushMask[x][y][z]: randomChance = random.randint(1, totalChance) diff --git a/stock-filters/AddPotionEffect.py b/stock-filters/AddPotionEffect.py index b50527469..3db573335 100755 --- a/stock-filters/AddPotionEffect.py +++ b/stock-filters/AddPotionEffect.py @@ -55,7 +55,7 @@ def perform(level, box, options): y = e["Pos"][1].value z = e["Pos"][2].value - if x >= box.minx and x < box.maxx and y >= box.miny and y < box.maxy and z >= box.minz and z < box.maxz: + if box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz: if "Health" in e: if "ActiveEffects" not in e: e["ActiveEffects"] = TAG_List() diff --git a/stock-filters/BanSlimes.py b/stock-filters/BanSlimes.py index 44e3aecce..ecbedf260 100755 --- a/stock-filters/BanSlimes.py +++ b/stock-filters/BanSlimes.py @@ -6,6 +6,7 @@ # This mimics some of the functionality from the Java Random class. # Java Random source code can be found here: http://developer.classpath.org/doc/java/util/Random-source.html + class Random: def __init__(self, randseed): self.setSeed(randseed) diff --git a/stock-filters/ChangeMobs.py b/stock-filters/ChangeMobs.py index fd2677bc7..c4e80aa68 100755 --- a/stock-filters/ChangeMobs.py +++ b/stock-filters/ChangeMobs.py @@ -71,7 +71,7 @@ def perform(level, box, options): y = e["Pos"][1].value z = e["Pos"][2].value - if x >= box.minx and x < box.maxx and y >= box.miny and y < box.maxy and z >= box.minz and z < box.maxz: + if box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz: if "Health" in e: if health != noop: e["Health"] = TAG_Short(health) diff --git a/stock-filters/CreateBusses.py b/stock-filters/CreateBusses.py index 21035d530..8095f15ff 100755 --- a/stock-filters/CreateBusses.py +++ b/stock-filters/CreateBusses.py @@ -30,19 +30,19 @@ def perform(level, box, options): def getHorizDir((x1, y1, z1), (x2, y2, z2)): if abs(x2 - x1) > abs(z2 - z1): - return (sign(x2 - x1), 0, 0) + return sign(x2 - x1), 0, 0 else: - if (z2 == z1): - return (1, 0, 0) + if z2 == z1: + return 1, 0, 0 else: - return (0, 0, sign(z2 - z1)) + return 0, 0, sign(z2 - z1) def getSecondaryDir((x1, y1, z1), (x2, y2, z2)): if abs(x2 - x1) > abs(z2 - z1): - return (0, 0, sign(z2 - z1)) + return 0, 0, sign(z2 - z1) else: - return (sign(x2 - x1), 0, 0) + return sign(x2 - x1), 0, 0 def leftOf((dx1, dy1, dz1), (dx2, dy2, dz2)): @@ -50,11 +50,11 @@ def leftOf((dx1, dy1, dz1), (dx2, dy2, dz2)): def rotateRight((dx, dy, dz)): - return ((-dz, dy, dx)) + return -dz, dy, dx def rotateLeft((dx, dy, dz)): - return ((dz, dy, -dx)) + return dz, dy, -dx def allAdjacentSamePlane(dir, secondaryDir): @@ -169,7 +169,7 @@ def allAdjacentDown(dir, secondaryDir): def getDir((x, y, z), (dx, dy, dz)): - return (x + dx, y + dy, z + dz) + return x + dx, y + dy, z + dz def dist((x1, y1, z1), (x2, y2, z2)): @@ -185,7 +185,7 @@ def below((x1, y1, z1), (x2, y2, z2)): def insideBox(box, (x, y, z)): - return x >= box.minx and x < box.maxx and y >= box.miny and y < box.maxy and z >= box.minz and z < box.maxz + return box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz Colors = { @@ -225,7 +225,7 @@ def getTerminals(self): for y in xrange(self.box.miny, self.box.maxy): for z in xrange(self.box.minz, self.box.maxz): (color, start) = self.isTerminal((x, y, z)) - if color != None and start != None: + if color is not None and start is not None: if start: if color in self.starts: raise Exception("Duplicate starting point for " + Colors[color] + " bus") @@ -255,7 +255,6 @@ def getGuides(self): self.guides[color].append(rs) - def isTerminal(self, (x, y, z)): pos = (x, y, z) for dir in HorizDirs: @@ -276,9 +275,9 @@ def isTerminal(self, (x, y, z)): if self.getBlockDataAt(getDir(otherPos, Down)) != data: # the wool colors don't match continue - return (data, towards) + return data, towards - return (None, None) + return None, None def pickAllPaths(self): for color in range(0, 16): @@ -294,14 +293,14 @@ def pickPath(self, color): minGuide = None for guide in self.guides[color]: guideDist = dist(currentPos, guide) - if minDist == None or guideDist < minDist: + if minDist is None or guideDist < minDist: minDist = guideDist minGuide = guide if dist(currentPos, self.ends[color]) == 1: return - if minGuide == None: + if minGuide is None: return self.path[color] = self.path[color] + (minGuide,) @@ -317,17 +316,16 @@ def connectDots(self, color): prevGuide = None self.power = 1 for guide in self.path[color]: - if prevGuide != None: + if prevGuide is not None: self.createConnection(prevGuide, guide, color) prevGuide = guide - def createConnection(self, pos1, pos2, color): currentPos = pos1 while currentPos != pos2: - self.power = self.power + 1 + self.power += 1 hdir = getHorizDir(currentPos, pos2) secondaryDir = getSecondaryDir(currentPos, pos2) @@ -363,7 +361,6 @@ def createConnection(self, pos1, pos2, color): # raise Exception("Algorithm failed to create bus for " + Colors[color] + " wire.") return - def canPlaceRedstone(self, pos, fromPos, destinationPos, restrictions): if restrictions == 1 and above(pos, fromPos): # repeater return False @@ -409,7 +406,6 @@ def canPlaceRedstone(self, pos, fromPos, destinationPos, restrictions): return True - def placeRedstone(self, pos, color): self.setBlockAt(pos, 55) # redstone self.setBlockAt(getDir(pos, Down), 35, color) # wool @@ -471,4 +467,3 @@ def repeaterPointingAway(self, (x1, y1, z1), (x2, y2, z2)): return True return False - \ No newline at end of file diff --git a/stock-filters/CreateShops.py b/stock-filters/CreateShops.py index f55ccc101..c805e8284 100644 --- a/stock-filters/CreateShops.py +++ b/stock-filters/CreateShops.py @@ -21,151 +21,156 @@ displayName = "Create Shops" Professions = { - "Farmer (brown)": 0, - "Librarian (white)": 1, - "Priest (purple)": 2, - "Blacksmith (black apron)": 3, - "Butcher (white apron)": 4, - "Villager (green)": 5, - } - + "Farmer (brown)": 0, + "Librarian (white)": 1, + "Priest (purple)": 2, + "Blacksmith (black apron)": 3, + "Butcher (white apron)": 4, + "Villager (green)": 5, +} + ProfessionKeys = () for key in Professions.keys(): - ProfessionKeys = ProfessionKeys + (key,) - -inputs = [( ("General Trade","title"), - ("This is a modified version of SethBling's Create Shops filter at DragonQuiz's request","label"), - ("Profession", ProfessionKeys), - ("Add Stopping Trade", True), - ("Invulnerable Villager", True), - ("Make Unlimited Trades", True), - ("Give Experience per a Trade", True), - ("Make Villager not Move", False), - ("Villager Name",("string","width=250")),), - - (("Rotation","title"), - (" Rotate the Position of your Trader\n" - "*Can only be used if Not Move is checked*","label"), - ("Y-Axis",(0, -180, 180)), - ("Changes its body rotation. Due west is 0. Must be between -180 to 180 degrees.","label"), - ("X-Axis",(0, -90, 90)), - ("Changes the head rotation Horizontal is 0. Positive values look downward. Must be between -90 to 90 degrees","label"), - ), - - (("Trade Notes","title"), - ("To create a shop first put your buy in the top slot(s) of the chest.\n" - "Second put a second buy in the middle slot(optional).\n" - "Third put a sell in the bottom slot.\n" - "Click the chest you want and choose what you want and click hit enter\n" - "*All items must be in the same row*\n" - ,"label")), - ] - + ProfessionKeys = ProfessionKeys + (key,) + +inputs = [( ("General Trade", "title"), + ("This is a modified version of SethBling's Create Shops filter at DragonQuiz's request", "label"), + ("Profession", ProfessionKeys), + ("Add Stopping Trade", True), + ("Invulnerable Villager", True), + ("Make Unlimited Trades", True), + ("Give Experience per a Trade", True), + ("Make Villager not Move", False), + ("Villager Name", ("string", "width=250")),), + + (("Rotation", "title"), + (" Rotate the Position of your Trader\n" + "*Can only be used if Not Move is checked*", "label"), + ("Y-Axis", (0, -180, 180)), + ("Changes its body rotation. Due west is 0. Must be between -180 to 180 degrees.", "label"), + ("X-Axis", (0, -90, 90)), + ( + "Changes the head rotation Horizontal is 0. Positive values look downward. Must be between -90 to 90 degrees", + "label"), + ), + + (("Trade Notes", "title"), + ("To create a shop first put your buy in the top slot(s) of the chest.\n" + "Second put a second buy in the middle slot(optional).\n" + "Third put a sell in the bottom slot.\n" + "Click the chest you want and choose what you want and click hit enter\n" + "*All items must be in the same row*\n" + , "label")), +] + + def perform(level, box, options): - emptyTrade = options["Add Stopping Trade"] - invincible = options["Invulnerable Villager"] - unlimited = options["Make Unlimited Trades"] - xp = options["Give Experience per a Trade"] - nomove = options["Make Villager not Move"] - name = options["Villager Name"] - yaxis = options["Y-Axis"] - xaxis = options["X-Axis"] - for (chunk, slices, point) in level.getChunkSlices(box): - for e in chunk.TileEntities: - x = e["x"].value - y = e["y"].value - z = e["z"].value - - if (x,y,z) in box: - if e["id"].value == "Chest": - createShop(level, x, y, z, emptyTrade, invincible, Professions[options["Profession"]], unlimited, xp, nomove, name, yaxis, xaxis) + emptyTrade = options["Add Stopping Trade"] + invincible = options["Invulnerable Villager"] + unlimited = options["Make Unlimited Trades"] + xp = options["Give Experience per a Trade"] + nomove = options["Make Villager not Move"] + name = options["Villager Name"] + yaxis = options["Y-Axis"] + xaxis = options["X-Axis"] + for (chunk, slices, point) in level.getChunkSlices(box): + for e in chunk.TileEntities: + x = e["x"].value + y = e["y"].value + z = e["z"].value + + if (x, y, z) in box: + if e["id"].value == "Chest": + createShop(level, x, y, z, emptyTrade, invincible, Professions[options["Profession"]], unlimited, + xp, nomove, name, yaxis, xaxis) + def createShop(level, x, y, z, emptyTrade, invincible, profession, unlimited, xp, nomove, name, yaxis, xaxis): - chest = level.tileEntityAt(x, y, z) - if chest == None: - return - - priceList = {} - priceListB = {} - saleList = {} - - for item in chest["Items"]: - slot = item["Slot"].value - if slot >= 0 and slot <= 8: - priceList[slot] = item - elif slot >= 9 and slot <= 17: - priceListB[slot-9] = item - elif slot >= 18 and slot <= 26: - saleList[slot-18] = item - - villager = TAG_Compound() - villager["PersistenceRequired"] = TAG_Byte(1) - villager["OnGround"] = TAG_Byte(1) - villager["Air"] = TAG_Short(300) - villager["AttackTime"] = TAG_Short(0) - villager["DeathTime"] = TAG_Short(0) - villager["Fire"] = TAG_Short(-1) - villager["Health"] = TAG_Short(20) - villager["HurtTime"] = TAG_Short(0) - villager["Age"] = TAG_Int(0) - villager["Profession"] = TAG_Int(profession) - villager["Career"] = TAG_Int(1) - villager["CareerLevel"] = TAG_Int(1000) - villager["Riches"] = TAG_Int(200) - villager["FallDistance"] = TAG_Float(0) - villager["CustomNameVisible"] = TAG_Byte(1) - villager["CustomName"] = TAG_String(name) - villager["Invulnerable"] = TAG_Byte(invincible) - villager["NoAI"] = TAG_Byte(nomove) - villager["id"] = TAG_String("Villager") - villager["Motion"] = TAG_List([TAG_Double(0.0), TAG_Double(0.0), TAG_Double(0.0)]) - villager["Pos"] = TAG_List ([TAG_Double(x + 0.5), TAG_Double(y), TAG_Double(z + 0.5)]) - villager["Rotation"] = TAG_List([TAG_Float(yaxis), TAG_Float(xaxis)]) - - villager["Willing"] = TAG_Byte(0) - villager["Offers"] = TAG_Compound() - villager["Offers"]["Recipes"] = TAG_List() - for i in range(9): - if (i in priceList or i in priceListB) and i in saleList: - offer = TAG_Compound() - if xp: - offer["rewardExp"] = TAG_Byte(1) - else: - offer["rewardExp"] = TAG_Byte(0) - - if unlimited: - offer["uses"] = TAG_Int(0) - offer["maxUses"] = TAG_Int(2000000000) - else: - offer["uses"] = TAG_Int(0) - offer["maxUses"] = TAG_Int(1) - - if i in priceList: - offer["buy"] = priceList[i] - if i in priceListB: - if i in priceList: - offer["buyB"] = priceListB[i] - else: - offer["buy"] = priceListB[i] - - offer["sell"] = saleList[i] - villager["Offers"]["Recipes"].append(offer) - - if emptyTrade: - offer = TAG_Compound() - offer["buy"] = TAG_Compound() - offer["buy"]["Count"] = TAG_Byte(1) - offer["buy"]["Damage"] = TAG_Short(0) - offer["buy"]["id"] = TAG_String("minecraft:barrier") - offer["sell"] = TAG_Compound() - offer["sell"]["Count"] = TAG_Byte(1) - offer["sell"]["Damage"] = TAG_Short(0) - offer["sell"]["id"] = TAG_String("minecraft:barrier") - villager["Offers"]["Recipes"].append(offer) - - level.setBlockAt(x, y, z, 0) - - chunk = level.getChunk(x / 16, z / 16) - chunk.Entities.append(villager) - chunk.TileEntities.remove(chest) - chunk.dirty = True + chest = level.tileEntityAt(x, y, z) + if chest is None: + return + + priceList = {} + priceListB = {} + saleList = {} + + for item in chest["Items"]: + slot = item["Slot"].value + if 0 <= slot <= 8: + priceList[slot] = item + elif 9 <= slot <= 17: + priceListB[slot - 9] = item + elif 18 <= slot <= 26: + saleList[slot - 18] = item + + villager = TAG_Compound() + villager["PersistenceRequired"] = TAG_Byte(1) + villager["OnGround"] = TAG_Byte(1) + villager["Air"] = TAG_Short(300) + villager["AttackTime"] = TAG_Short(0) + villager["DeathTime"] = TAG_Short(0) + villager["Fire"] = TAG_Short(-1) + villager["Health"] = TAG_Short(20) + villager["HurtTime"] = TAG_Short(0) + villager["Age"] = TAG_Int(0) + villager["Profession"] = TAG_Int(profession) + villager["Career"] = TAG_Int(1) + villager["CareerLevel"] = TAG_Int(1000) + villager["Riches"] = TAG_Int(200) + villager["FallDistance"] = TAG_Float(0) + villager["CustomNameVisible"] = TAG_Byte(1) + villager["CustomName"] = TAG_String(name) + villager["Invulnerable"] = TAG_Byte(invincible) + villager["NoAI"] = TAG_Byte(nomove) + villager["id"] = TAG_String("Villager") + villager["Motion"] = TAG_List([TAG_Double(0.0), TAG_Double(0.0), TAG_Double(0.0)]) + villager["Pos"] = TAG_List([TAG_Double(x + 0.5), TAG_Double(y), TAG_Double(z + 0.5)]) + villager["Rotation"] = TAG_List([TAG_Float(yaxis), TAG_Float(xaxis)]) + + villager["Willing"] = TAG_Byte(0) + villager["Offers"] = TAG_Compound() + villager["Offers"]["Recipes"] = TAG_List() + for i in range(9): + if (i in priceList or i in priceListB) and i in saleList: + offer = TAG_Compound() + if xp: + offer["rewardExp"] = TAG_Byte(1) + else: + offer["rewardExp"] = TAG_Byte(0) + + if unlimited: + offer["uses"] = TAG_Int(0) + offer["maxUses"] = TAG_Int(2000000000) + else: + offer["uses"] = TAG_Int(0) + offer["maxUses"] = TAG_Int(1) + + if i in priceList: + offer["buy"] = priceList[i] + if i in priceListB: + if i in priceList: + offer["buyB"] = priceListB[i] + else: + offer["buy"] = priceListB[i] + + offer["sell"] = saleList[i] + villager["Offers"]["Recipes"].append(offer) + + if emptyTrade: + offer = TAG_Compound() + offer["buy"] = TAG_Compound() + offer["buy"]["Count"] = TAG_Byte(1) + offer["buy"]["Damage"] = TAG_Short(0) + offer["buy"]["id"] = TAG_String("minecraft:barrier") + offer["sell"] = TAG_Compound() + offer["sell"]["Count"] = TAG_Byte(1) + offer["sell"]["Damage"] = TAG_Short(0) + offer["sell"]["id"] = TAG_String("minecraft:barrier") + villager["Offers"]["Recipes"].append(offer) + + level.setBlockAt(x, y, z, 0) + + chunk = level.getChunk(x / 16, z / 16) + chunk.Entities.append(villager) + chunk.TileEntities.remove(chest) + chunk.dirty = True diff --git a/stock-filters/CreateSpawners.py b/stock-filters/CreateSpawners.py index 244e50716..3d1ca5f9e 100755 --- a/stock-filters/CreateSpawners.py +++ b/stock-filters/CreateSpawners.py @@ -30,7 +30,7 @@ def perform(level, box, options): y = int(entity["Pos"][1].value) z = int(entity["Pos"][2].value) - if x >= box.minx and x < box.maxx and y >= box.miny and y < box.maxy and z >= box.minz and z < box.maxz: + if box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz: entitiesToRemove.append((chunk, entity)) level.setBlockAt(x, y, z, 52) diff --git a/stock-filters/Find.py b/stock-filters/Find.py index 90839c901..ca5d5bc25 100644 --- a/stock-filters/Find.py +++ b/stock-filters/Find.py @@ -1,52 +1,54 @@ -#written by texelelf -from pymclevel import TAG_Byte, TAG_Short, TAG_Int, TAG_Compound, TAG_List, TAG_String, TAG_Double, TAG_Float, TAG_Long, TAG_Byte_Array, TAG_Int_Array +# written by texelelf +from pymclevel import TAG_Byte, TAG_Short, TAG_Int, TAG_Compound, TAG_List, TAG_String, TAG_Double, TAG_Float, TAG_Long, \ + TAG_Byte_Array, TAG_Int_Array from pymclevel.box import BoundingBox displayName = "Find" -tagtypes = { "TAG_Byte":0, "TAG_Short":1, "TAG_Int":2, "TAG_Compound":3, "TAG_List":4, "TAG_String":5, - "TAG_Double":6, "TAG_Float":7, "TAG_Long":8, "TAG_Byte_Array":9, "TAG_Int_Array":10 } - -tagses = { 0:TAG_Byte, 1:TAG_Short, 2:TAG_Int, 3:TAG_Compound, 4:TAG_List, 5:TAG_String, - 6:TAG_Double, 7:TAG_Float, 8:TAG_Long, 9:TAG_Byte_Array, 10:TAG_Int_Array, "Any":11} - -inputs = [ (("Match by:",("TileEntity","Entity","Block")), - ("Match block type (for TileEntity searches):", False), - ("Match block:","blocktype"), - ("Match block data:", True), - ("Match tile entities (for Block searches):", False), - ("\"None\" for Name or Value will match any tag's Name or Value respectively.","label"), - ("Match Tag Name:",("string","value=None")), - ("Match Tag Value:",("string","value=None")), - ("Case insensitive:",True), - ("Match Tag Type:",tuple(("Any",))+tuple(tagtypes.keys())), - ("Operation:",("Start New Search","Find Next","Dump Found Coordinates")), - ("Options","title")), - - (("Documentation","title"), - ("This filter is designed to search for NBT in either Entities or TileEntities. " - "It can also be used to search for blocks. \"Match by\" determines which type of object " - "is prioritized during the search. Entites and TileEntities will search relatively quickly, " - "while the speed of searching by Block will be directly proportional to the selection size (since every " - "single block within the selection will be examined). " - "All Entity searches will ignore the block settings; TileEntity searches will try to " - "\"Match block type\" if checked, and Block searches will try to \"Match tile entity\" tags if " - "checked. It is faster to match TileEntity searches with a Block Type than vice versa. Block " - "matching can also optionally match block data, e.g. matching all torches, or only torches facing " - "a specific direction.\n\"Start New Search\" will re-search through the selected volume, while \"Find Next\" " - "will iterate through the search results of the previous search.","label")) - ] +tagtypes = {"TAG_Byte": 0, "TAG_Short": 1, "TAG_Int": 2, "TAG_Compound": 3, "TAG_List": 4, "TAG_String": 5, + "TAG_Double": 6, "TAG_Float": 7, "TAG_Long": 8, "TAG_Byte_Array": 9, "TAG_Int_Array": 10} + +tagses = {0: TAG_Byte, 1: TAG_Short, 2: TAG_Int, 3: TAG_Compound, 4: TAG_List, 5: TAG_String, + 6: TAG_Double, 7: TAG_Float, 8: TAG_Long, 9: TAG_Byte_Array, 10: TAG_Int_Array, "Any": 11} + +inputs = [(("Match by:", ("TileEntity", "Entity", "Block")), + ("Match block type (for TileEntity searches):", False), + ("Match block:", "blocktype"), + ("Match block data:", True), + ("Match tile entities (for Block searches):", False), + ("\"None\" for Name or Value will match any tag's Name or Value respectively.", "label"), + ("Match Tag Name:", ("string", "value=None")), + ("Match Tag Value:", ("string", "value=None")), + ("Case insensitive:", True), + ("Match Tag Type:", tuple(("Any",)) + tuple(tagtypes.keys())), + ("Operation:", ("Start New Search", "Find Next", "Dump Found Coordinates")), + ("Options", "title")), + + (("Documentation", "title"), + ("This filter is designed to search for NBT in either Entities or TileEntities. " + "It can also be used to search for blocks. \"Match by\" determines which type of object " + "is prioritized during the search. Entites and TileEntities will search relatively quickly, " + "while the speed of searching by Block will be directly proportional to the selection size (since every " + "single block within the selection will be examined). " + "All Entity searches will ignore the block settings; TileEntity searches will try to " + "\"Match block type\" if checked, and Block searches will try to \"Match tile entity\" tags if " + "checked. It is faster to match TileEntity searches with a Block Type than vice versa. Block " + "matching can also optionally match block data, e.g. matching all torches, or only torches facing " + "a specific direction.\n\"Start New Search\" will re-search through the selected volume, while \"Find Next\" " + "will iterate through the search results of the previous search.", "label")) +] try: search except NameError: search = None -def FindTagS(nbtData,name,value,tagtype): + +def FindTagS(nbtData, name, value, tagtype): if type(nbtData) is TAG_List or type(nbtData) is TAG_Compound: if name in nbtData.name or name == "": if value == "": - if (type(nbtData) is tagtype or tagtype == 11): + if type(nbtData) is tagtype or tagtype == 11: print "found in pre-area" return True if type(nbtData) is TAG_List: @@ -54,17 +56,17 @@ def FindTagS(nbtData,name,value,tagtype): else: list = False - for tag in range(0,len(nbtData)) if list else nbtData.keys(): + for tag in range(0, len(nbtData)) if list else nbtData.keys(): if type(nbtData[tag]) is TAG_Compound: - if FindTagS(nbtData[tag],name,value,tagtype): + if FindTagS(nbtData[tag], name, value, tagtype): return True elif type(nbtData[tag]) is TAG_List: - if FindTagS(nbtData[tag],name,value,tagtype): + if FindTagS(nbtData[tag], name, value, tagtype): return True else: if name in nbtData[tag].name or name == "": if value in unicode(nbtData[tag].value): - if (type(nbtData[tag]) is tagtype or tagtype == 11): + if type(nbtData[tag]) is tagtype or tagtype == 11: print "found in list/compound" return True else: @@ -72,48 +74,51 @@ def FindTagS(nbtData,name,value,tagtype): else: if name in nbtData.name or name == "": if value in unicode(nbtData.value): - if (type(nbtData[tag]) is tagtype or tagtype == 11): + if type(nbtData[tag]) is tagtype or tagtype == 11: print "found outside" return True return False -def FindTagI(nbtData,name,value,tagtype): + +def FindTagI(nbtData, name, value, tagtype): if type(nbtData) is TAG_List or type(nbtData) is TAG_Compound: if name in nbtData.name.upper() or name == "": if value == "": - if (type(nbtData) is tagtype or tagtype == 11): + if type(nbtData) is tagtype or tagtype == 11: return True if type(nbtData) is TAG_List: list = True else: list = False - for tag in range(0,len(nbtData)) if list else nbtData.keys(): + for tag in range(0, len(nbtData)) if list else nbtData.keys(): if type(nbtData[tag]) is TAG_Compound: - if FindTagI(nbtData[tag],name,value,tagtype): + if FindTagI(nbtData[tag], name, value, tagtype): return True elif type(nbtData[tag]) is TAG_List: - if FindTagI(nbtData[tag],name,value,tagtype): + if FindTagI(nbtData[tag], name, value, tagtype): return True else: if name in nbtData[tag].name.upper() or name == "": if value in unicode(nbtData[tag].value).upper(): - if (type(nbtData[tag]) is tagtype or tagtype == 11): + if type(nbtData[tag]) is tagtype or tagtype == 11: return True else: return False else: if name in nbtData.name.upper() or name == "": if value in unicode(nbtData.value).upper(): - if (type(nbtData[tag]) is tagtype or tagtype == 11): + if type(nbtData[tag]) is tagtype or tagtype == 11: return True return False -def FindTag(nbtData,name,value,tagtype,caseSensitive): + +def FindTag(nbtData, name, value, tagtype, caseSensitive): if caseSensitive: - return FindTagS(nbtData,name,value,tagtype) + return FindTagS(nbtData, name, value, tagtype) else: - return FindTagI(nbtData,name,value,tagtype) + return FindTagI(nbtData, name, value, tagtype) + def perform(level, box, options): global search @@ -136,7 +141,7 @@ def perform(level, box, options): if matchtile and matchname == "" and matchval == "": raise Exception("\nInvalid Tag Name and Value; the present values will match every tag of the specified type.") - if search == None or op == "Start New Search" or op == "Dump Found Coordinates": + if search is None or op == "Start New Search" or op == "Dump Found Coordinates": search = [] if not search: @@ -144,63 +149,63 @@ def perform(level, box, options): for x in xrange(box.minx, box.maxx): for z in xrange(box.minz, box.maxz): for y in xrange(box.miny, box.maxy): - block = level.blockAt(x,y,z) - data = level.blockDataAt(x,y,z) + block = level.blockAt(x, y, z) + data = level.blockDataAt(x, y, z) if block == matchblock.ID and (not matchdata or data == matchblock.blockData): pass else: continue if matchtile: - tile = level.tileEntityAt(x,y,z) - if tile != None: - if not FindTag(tile,matchname,matchval,tagses[matchtagtype],caseSensitive): + tile = level.tileEntityAt(x, y, z) + if tile is not None: + if not FindTag(tile, matchname, matchval, tagses[matchtagtype], caseSensitive): continue else: continue - search.append((x,y,z)) + search.append((x, y, z)) elif by == "TileEntity": for (chunk, _, _) in level.getChunkSlices(box): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value - if (x,y,z) in box: + if (x, y, z) in box: if matchtype: - block = level.blockAt(x,y,z) - data = level.blockDataAt(x,y,z) + block = level.blockAt(x, y, z) + data = level.blockDataAt(x, y, z) if block == matchblock.ID and (not matchdata or data == matchblock.blockData): pass else: continue - if not FindTag(e,matchname,matchval,tagses[matchtagtype],caseSensitive): + if not FindTag(e, matchname, matchval, tagses[matchtagtype], caseSensitive): continue - search.append((x,y,z)) + search.append((x, y, z)) else: for (chunk, _, _) in level.getChunkSlices(box): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value - if (x,y,z) in box: - if FindTag(e,matchname,matchval,tagses[matchtagtype],caseSensitive): - search.append((x,y,z)) + if (x, y, z) in box: + if FindTag(e, matchname, matchval, tagses[matchtagtype], caseSensitive): + search.append((x, y, z)) if not search: raise Exception("\nNo matching blocks/tile entities found") else: search.sort() if op == "Dump Found Coordinates": - raise Exception("\nMatching Coordinates:\n"+"\n".join("%d, %d, %d" % pos for pos in search)) + raise Exception("\nMatching Coordinates:\n" + "\n".join("%d, %d, %d" % pos for pos in search)) else: for s in search: - editor.mainViewport.cameraPosition = (s[0]+0.5,s[1]+2,s[2]-1) + editor.mainViewport.cameraPosition = (s[0] + 0.5, s[1] + 2, s[2] - 1) editor.mainViewport.yaw = 0.0 editor.mainViewport.pitch = 45.0 - newBox = BoundingBox(s, (1,1,1)) + newBox = BoundingBox(s, (1, 1, 1)) editor.selectionTool.setSelection(newBox) - if not editor.YesNoWidget("Matching blocks/tile entities found at "+str(s)+".\nContinue search?"): + if not editor.YesNoWidget("Matching blocks/tile entities found at " + str(s) + ".\nContinue search?"): raise Exception("\nSearch halted.") else: raise Exception("\nEnd of search.") diff --git a/stock-filters/Forester.py b/stock-filters/Forester.py index 114a30a07..4ffde331f 100755 --- a/stock-filters/Forester.py +++ b/stock-filters/Forester.py @@ -565,7 +565,7 @@ def makefoliage(self, mcmap): start = self.pos[1] end = self.pos[1] + self.height + 1 for y in range(start, end): - for i in [0, 1]: + for _ in [0, 1]: xoff = choice([-1, 1]) zoff = choice([-1, 1]) x = self.pos[0] + xoff @@ -598,7 +598,8 @@ class ProceduralTree(Tree): Subclass 'prepare' and 'shapefunc' to make different shaped trees. ''' - def crossection(self, center, radius, diraxis, matidx, mcmap): + @staticmethod + def crossection(center, radius, diraxis, matidx, mcmap): '''Create a round section of type matidx in mcmap. Passed values: @@ -910,7 +911,7 @@ def maketrunk(self, mcmap): posradius = trunkradius # In mangroves, the root buttresses are much more extended. if SHAPE == "mangrove": - posradius = posradius * 2.618 + posradius *= 2.618 num_of_buttresses = int(sqrt(trunkradius) + 3.5) for i in range(num_of_buttresses): rndang = random() * 2 * pi @@ -1055,8 +1056,8 @@ def prepare(self, mcmap): self.branchslope = 0.382 ProceduralTree.prepare(self, mcmap) self.foliage_shape = [2, 3, 3, 2.5, 1.6] - self.trunkradius = self.trunkradius * 0.8 - self.trunkheight = TRUNKHEIGHT * self.trunkheight + self.trunkradius *= 0.8 + self.trunkheight *= TRUNKHEIGHT def shapefunc(self, y): twigs = ProceduralTree.shapefunc(self, y) @@ -1072,7 +1073,7 @@ def shapefunc(self, y): dist = 0 else: dist = sqrt((radius ** 2) - (adj ** 2)) - dist = dist * .618 + dist *= .618 return dist @@ -1086,7 +1087,7 @@ def prepare(self, mcmap): self.branchslope = 0.15 ProceduralTree.prepare(self, mcmap) self.foliage_shape = [3, 2.6, 2, 1] - self.trunkradius = self.trunkradius * 0.5 + self.trunkradius *= 0.5 def shapefunc(self, y): twigs = ProceduralTree.shapefunc(self, y) @@ -1108,8 +1109,8 @@ def prepare(self, mcmap): self.foliage_shape = [3.4, 2.6] self.branchslope = 1.0 ProceduralTree.prepare(self, mcmap) - self.trunkradius = self.trunkradius * 0.382 - self.trunkheight = self.trunkheight * .9 + self.trunkradius *= 0.382 + self.trunkheight *= .9 def shapefunc(self, y): if y < self.height * 0.8: @@ -1132,13 +1133,13 @@ class MangroveTree(RoundTree): def prepare(self, mcmap): self.branchslope = 1.0 RoundTree.prepare(self, mcmap) - self.trunkradius = self.trunkradius * 0.618 + self.trunkradius *= 0.618 def shapefunc(self, y): val = RoundTree.shapefunc(self, y) if val is None: return val - val = val * 1.618 + val *= 1.618 return val diff --git a/stock-filters/Invincible.py b/stock-filters/Invincible.py index 4ca9b16c5..47c863c08 100755 --- a/stock-filters/Invincible.py +++ b/stock-filters/Invincible.py @@ -17,7 +17,7 @@ def perform(level, box, options): y = e["Pos"][1].value z = e["Pos"][2].value - if x >= box.minx and x < box.maxx and y >= box.miny and y < box.maxy and z >= box.minz and z < box.maxz: + if box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz: if "Health" in e: if "ActiveEffects" not in e: e["ActiveEffects"] = TAG_List() diff --git a/stock-filters/colorwires.py b/stock-filters/colorwires.py index a2b979291..3d1cc76a4 100755 --- a/stock-filters/colorwires.py +++ b/stock-filters/colorwires.py @@ -22,7 +22,8 @@ class RedstoneGroups: def __init__(self, level): self.level = level - def isRedstone(self, blockid): + @staticmethod + def isRedstone(blockid): return blockid == 55 or blockid == 93 or blockid == 94 def testblock(self, pos): @@ -33,11 +34,11 @@ def testblock(self, pos): return self.group[pos] = self.currentgroup self.testneighbors(pos) - self.currentgroup = self.currentgroup + 1 + self.currentgroup += 1 def testneighbors(self, (x, y, z)): for dy in xrange(-1, 2, 1): - if y + dy >= 0 and y + dy <= 255: + if 0 <= dy + y + dy <= 255: self.testneighbor((x, y, z), (x - 1, y + dy, z)) self.testneighbor((x, y, z), (x + 1, y + dy, z)) self.testneighbor((x, y, z), (x, y + dy, z - 1)) @@ -104,7 +105,6 @@ def repeaterPointingAway(self, (x1, y1, z1), (x2, y2, z2)): return False - def connected(self, (x1, y1, z1), (x2, y2, z2)): blockid1 = self.level.blockAt(x1, y1, z1) blockid2 = self.level.blockAt(x2, y2, z2) diff --git a/stock-filters/decliff.py b/stock-filters/decliff.py index 4d853783c..695070897 100755 --- a/stock-filters/decliff.py +++ b/stock-filters/decliff.py @@ -117,7 +117,7 @@ def adjheight(orig, new, slice_no, cliff_pos, dir, adj, can_adj, maxstep, slice_ new[slice_no, cur_pos] = max([0, orig[slice_no, cur_pos] + cur_adj]) if cur_adj != 0 and \ abs(prev) < abs(int(adj * done_adj / can_adj)): - cur_adj = cur_adj + (prev - int(adj * done_adj / can_adj)) + cur_adj += prev - int(adj * done_adj / can_adj) prev = int(adj * done_adj / can_adj) new[slice_no, end] = orig[slice_no, end] @@ -189,7 +189,7 @@ def perform(level, box, options): if can_left > 0 and RLOption == "Lower Only": can_left = 0 - if cliff_height < 0 and can_right - can_left < cliff_height: + if 0 > cliff_height > can_right - can_left: if abs(can_left) > abs(can_right): adj_left = -1 * (cliff_height - max([int(cliff_height / 2), can_right])) adj_right = cliff_height + adj_left @@ -197,7 +197,7 @@ def perform(level, box, options): adj_right = cliff_height - max([int(cliff_height / 2), -can_left]) adj_left = -1 * (cliff_height - adj_right + 1) else: - if cliff_height > 0 and can_right - can_left > cliff_height: + if 0 < cliff_height < can_right - can_left: if abs(can_left) > abs(can_right): adj_left = -1 * (cliff_height - min([int(cliff_height / 2), can_right])) adj_right = cliff_height + adj_left @@ -238,7 +238,7 @@ def perform(level, box, options): if column[cur_pos:cur_pos + 1] != am.Water.ID and \ column[cur_pos:cur_pos + 1] != am.Ice.ID: break - Waterdepth = Waterdepth + 1 + Waterdepth += 1 if delta == 0: column[oh:] = schema.Blocks[x, z, oh:] diff --git a/stock-filters/demo/Test.py b/stock-filters/demo/Test.py index c539beadb..eac488a64 100755 --- a/stock-filters/demo/Test.py +++ b/stock-filters/demo/Test.py @@ -17,6 +17,7 @@ ("Float Field Test (Increments by 0.3)", (0.0, -5.0, 5.0, 0.3)), ) + class StoreData: def __init__(self): self._isFork = False @@ -80,7 +81,7 @@ def perform(level, box, options): chunks.append(chunk) thing = ( ("Entity", tuple(sorted(entities.keys()))), - ("Entity Name", ("string")), + ("Entity Name", "string"), ("Replace existing names?", False), ) result = editor.addExternalWidget(thing) diff --git a/stock-filters/demo/filterdemo.py b/stock-filters/demo/filterdemo.py index 963663f9d..4039bd21d 100755 --- a/stock-filters/demo/filterdemo.py +++ b/stock-filters/demo/filterdemo.py @@ -41,8 +41,6 @@ def perform(level, box, options): - blockType = options["Pick a block:"].ID - complexity = options["Fractal complexity"] if options["Enable thrusters"]: # Errors will alert the user and print a traceback to the console. raise NotImplementedError("Thrusters not attached!") @@ -61,7 +59,6 @@ def perform(level, box, options): if level.blockAt(x, y, z) == 14: level.setBlockAt(x, y, z, 46) - # The second is to extract the segment of interest into a contiguous array # using level.extractSchematic. this simplifies using numpy but at the cost # of the temporary buffer and the risk of a memory error on 32-bit systems. diff --git a/stock-filters/mcInterface.py b/stock-filters/mcInterface.py index 75c3ae54f..79eb71723 100755 --- a/stock-filters/mcInterface.py +++ b/stock-filters/mcInterface.py @@ -26,9 +26,7 @@ def check_box_3d(self, x, y, z): def block(self, x, y, z): if not self.check_box_3d(x, y, z): return None - d = {} - d['B'] = self.level.blockAt(x, y, z) - d['D'] = self.level.blockDataAt(x, y, z) + d = {'B': self.level.blockAt(x, y, z), 'D': self.level.blockDataAt(x, y, z)} return d def set_block(self, x, y, z, d): diff --git a/stock-filters/setbiome.py b/stock-filters/setbiome.py index f7363a4b6..43a0e1d68 100755 --- a/stock-filters/setbiome.py +++ b/stock-filters/setbiome.py @@ -14,7 +14,7 @@ from numpy import zeros inputs = ( - ("Biome", ( "Ocean", + ("Biome", ("Ocean", "Plains", "Desert", "Extreme Hills", diff --git a/stock-filters/surfacerepair.py b/stock-filters/surfacerepair.py index 4e0d38410..20a1bd063 100755 --- a/stock-filters/surfacerepair.py +++ b/stock-filters/surfacerepair.py @@ -38,8 +38,6 @@ def perform(level, box, options): h = heightmap[x, z] h2 = heightmap[z, x] - b2 = blocks[z, x, h2] - if blocks[x, z, h] == 1: h += 2 # rock surface - top 4 layers become 2 air and 2 rock if blocks[z, x, h2] == 1: diff --git a/utilities/gl_display_context.py b/utilities/gl_display_context.py index 770044c21..1f991b573 100644 --- a/utilities/gl_display_context.py +++ b/utilities/gl_display_context.py @@ -20,11 +20,13 @@ class GLDisplayContext(object): def __init__(self, splash=None): self.reset(splash) - def getWindowSize(self): + @staticmethod + def getWindowSize(): w, h = (config.settings.windowWidth.get(), config.settings.windowHeight.get()) return max(20, w), max(20, h) - def displayMode(self): + @staticmethod + def displayMode(): return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF def reset(self, splash=None): @@ -66,7 +68,6 @@ def reset(self, splash=None): X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: - w, h = self.getWindowSize() hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner) diff --git a/utilities/md5_utility.py b/utilities/md5_utility.py index b93f5a599..b4a801438 100644 --- a/utilities/md5_utility.py +++ b/utilities/md5_utility.py @@ -5,9 +5,11 @@ import os import time + class NotAModule(Exception): pass + def getMD5Hash(url, name): print "["+str(time.ctime())+"][MD5 Hasher] Downloading <"+name+">" urllib.urlretrieve(url, name) @@ -16,11 +18,11 @@ def getMD5Hash(url, name): print "["+str(time.ctime())+"][MD5 Hasher] Finished downloading <"+name+">" return hashlib.md5(data).hexdigest() + def getMD5HashesForRelease(): files = [] flines = [] release_api_response = json.loads(urllib2.urlopen("https://api.github.com/repos/Khroki/MCEdit-Unified/releases").read()) - tag = release_api_response[0]["tag_name"] print "["+str(time.ctime())+"][MD5 Hasher] Looping through collected assets" for asset in release_api_response[0]["assets"]: if "Win" in asset["name"]: diff --git a/version_utils.py b/version_utils.py index 968306cf8..133ca1c92 100644 --- a/version_utils.py +++ b/version_utils.py @@ -24,6 +24,7 @@ #print getPlayerSkinURL('4566e69fc90748ee8d71d7ba5aa00d20') + class __PlayerCache: SUCCESS = 0 @@ -41,17 +42,12 @@ def __convert(self): if jsonFile is not None: for old_player in jsonFile.keys(): player = jsonFile[old_player] - new_player = {} - new_player["Playername"] = player["username"] - new_player["UUID (No Separator)"] = old_player.replace("-","") - new_player["UUID (Separator)"] = old_player - new_player["WasSuccessful"] = True - new_player["Timstamp"] = player["timestamp"] + new_player = {"Playername": player["username"], "UUID (No Separator)": old_player.replace("-", ""), + "UUID (Separator)": old_player, "WasSuccessful": True, "Timstamp": player["timestamp"]} self._playerCacheList.append(new_player) self._save() print "Convert usercache.json" - - + def __init__(self): self._playerCacheList = [] if not os.path.exists(userCachePath): @@ -60,13 +56,12 @@ def __init__(self): with open(userCachePath) as f: line = f.readline() if line.startswith("{"): - self.__convert(); + self.__convert() try: with open(userCachePath) as json_in: self._playerCacheList = json.load(json_in) except: print "usercache.json is corrupted" - def _save(self): with open(userCachePath, "w") as out: @@ -77,7 +72,7 @@ def _removePlayerWithName(self, name): for p in self._playerCacheList: if p["Playername"] == name: toRemove = p - if toRemove != None: + if toRemove is not None: self._playerCacheList.remove(toRemove) self._save() @@ -90,7 +85,7 @@ def _removePlayerWithUUID(self, uuid, seperator=True): else: if p["UUID (No Separator)"] == uuid: toRemove = p - if toRemove != None: + if toRemove is not None: self._playerCacheList.remove(toRemove) self._save() @@ -117,7 +112,6 @@ def getPlayerFromUUID(self, uuid, forceNetwork=False): if forceNetwork: if self.uuidInCache(uuid): self._removePlayerWithUUID(uuid) - response = None try: response = urllib2.urlopen("https://sessionserver.mojang.com/session/minecraft/profile/{}".format(uuid.replace("-",""))).read() except urllib2.URLError: @@ -148,16 +142,13 @@ def getPlayerFromPlayername(self, playername, forceNetwork=False, separator=True if forceNetwork: if self.nameInCache(playername): self._removePlayerWithName(playername) - response = None try: response = urllib2.urlopen("https://api.mojang.com/users/profiles/minecraft/{}".format(playername)).read() except urllib2.URLError: return playername if response is not None and response != "": playerJSON = json.loads(response) - player = {} - player["Playername"] = playername - player["UUID (No Separator)"] = playerJSON["id"] + player = {"Playername": playername, "UUID (No Separator)": playerJSON["id"]} uuid = playerJSON["id"][:4]+"-"+playerJSON["id"][4:8]+"-"+playerJSON["id"][8:12]+"-"+playerJSON["id"][12:16]+"-"+playerJSON["id"][16:] player["UUID (Separator)"] = uuid player["WasSuccessful"] = True @@ -192,9 +183,9 @@ def getAllPlayersKnown(self, returnType=0): for p in self._playerCacheList: toReturn[p["Playername"]] = p return toReturn - - - def __formats(self): + + @staticmethod + def __formats(): player = { "Playername":"", "UUID":"", @@ -206,6 +197,7 @@ def __formats(self): playercache = __PlayerCache() + def getUUIDFromPlayerName(player, seperator=True, forceNetwork=False): return playercache.getPlayerFromPlayername(player, forceNetwork, seperator) ''' @@ -270,6 +262,7 @@ def getUUIDFromPlayerName(player, seperator=True, forceNetwork=False): raise PlayerNotFound(player) ''' + def getPlayerNameFromUUID(uuid,forceNetwork=False): ''' Gets the Username from a UUID @@ -337,6 +330,7 @@ def getPlayerNameFromUUID(uuid,forceNetwork=False): return uuid ''' + def getPlayerSkin(uuid, force=False, trying_again=False, instance=None): SKIN_URL = "http://skins.minecraft.net/MinecraftSkins/{}.png" toReturn = 'char.png' @@ -369,7 +363,7 @@ def getPlayerSkin(uuid, force=False, trying_again=False, instance=None): except IOError: print "Couldn't find Image file ("+str(uuid.replace("-","_")+".png")+") or the file may be corrupted" print "Trying to re-download skin...." - if not trying_again and instance != None: + if not trying_again and instance is not None: instance.delete_skin(uuid) os.remove(os.path.join("player-skins", uuid.replace("-","_")+".png")) toReturn = getPlayerSkin(uuid, force=True, trying_again=True) @@ -378,7 +372,7 @@ def getPlayerSkin(uuid, force=False, trying_again=False, instance=None): print "Couldn't connect to a network" raise Exception("Could not connect to the skins server, please check your Internet connection and try again.") pass - except Exception, e: + except Exception: print "Unknown error occurred while reading/downloading skin for "+str(uuid.replace("-","_")+".png") pass return toReturn diff --git a/viewports/camera.py b/viewports/camera.py index 127708336..0e27f1e63 100644 --- a/viewports/camera.py +++ b/viewports/camera.py @@ -22,7 +22,8 @@ from OpenGL import GL from OpenGL import GLU -from albow import alert, AttrRef, Button, Column, input_text, Row, TableColumn, TableView, Widget, CheckBox, TextFieldWrapped +from albow import alert, AttrRef, Button, Column, input_text, Row, TableColumn, TableView, Widget, CheckBox, \ + TextFieldWrapped from albow.controls import Label, ValueDisplay from albow.dialogs import Dialog, wrapped_label from albow.openglwidgets import GLViewport @@ -64,7 +65,7 @@ def __init__(self, editor): # A state machine to dodge an apparent bug in pygame that generates erroneous mouse move events # 0 = bad event already happened - # 1 = app just started or regained focus since last bad event + # 1 = app just started or regained focus since last bad event # 2 = mouse cursor was hidden after state 1, next event will be bad self.avoidMouseJumpBug = 1 @@ -147,11 +148,11 @@ def tickCamera(self, frameStartTime, inputs, inSpace): mouseSpeed = config.controls.mouseSpeed.get() self.yaw += pi[0] * mouseSpeed self.pitch += pi[1] * mouseSpeed - + if config.settings.viewMode.get() == "Chunk": (dx, dy, dz) = (0, -0.25, -1) - self.yaw = yaw = -180 - self.pitch = pitch = 10 + self.yaw = -180 + self.pitch = 10 elif self.flyMode: (dx, dy, dz) = self._anglesToVector(self.yaw, 0) elif self.swapAxes: @@ -186,7 +187,7 @@ def tickCamera(self, frameStartTime, inputs, inSpace): # apply drag if speed: if self.autobrake and not any(inputs): - speed = 0.15 * speed + speed *= 0.15 else: sign = speed / abs(speed) @@ -234,7 +235,8 @@ def setModelview(self): def _cameraVector(self): return self._anglesToVector(self.yaw, self.pitch) - def _anglesToVector(self, yaw, pitch): + @staticmethod + def _anglesToVector(yaw, pitch): def nanzero(x): if isnan(x): return 0 @@ -302,7 +304,8 @@ def updateBlockFaceUnderCursor(self): if self.editor.mouseEntered: if not self.mouseMovesCamera: try: - focusPair = raycaster.firstBlock(self.cameraPosition, self._mouseVector(), self.editor.level, 100, config.settings.viewMode.get()) + focusPair = raycaster.firstBlock(self.cameraPosition, self._mouseVector(), self.editor.level, + 100, config.settings.viewMode.get()) except TooFarException: mouse3dPoint = self._blockUnderCursor() focusPair = self._findBlockFaceUnderCursor(mouse3dPoint) @@ -523,7 +526,6 @@ def redo(self): @mceutils.alertException def editSign(self, point): - block = self.editor.level.blockAt(*point) tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) @@ -618,8 +620,6 @@ def changeSign(): @mceutils.alertException def editSkull(self, point): - block = self.editor.level.blockAt(*point) - blockData = self.editor.level.blockDataAt(*point) tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) skullTypes = { @@ -712,8 +712,6 @@ def updateSkull(): @mceutils.alertException def editCommandBlock(self, point): panel = Dialog() - block = self.editor.level.blockAt(*point) - blockData = self.editor.level.blockDataAt(*point) tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) @@ -780,7 +778,8 @@ def updateCommandBlock(): okBTN = Button("OK", action=updateCommandBlock) cancel = Button("Cancel", action=panel.dismiss) - column = [titleLabel, Label("Command:"), commandField, Row((Label("Custom Name:"), nameField)), Row((Label("Track Output"), trackOutput)), okBTN, cancel] + column = [titleLabel, Label("Command:"), commandField, Row((Label("Custom Name:"), nameField)), + Row((Label("Track Output"), trackOutput)), okBTN, cancel] panel.add(Column(column)) panel.shrink_wrap() panel.present() @@ -908,7 +907,6 @@ def matches_itementity(e): for player in self.editor.level.players: tag = self.editor.level.getPlayerTag(player) - l = len(tag["Inventory"]) tag["Inventory"].value = [t for t in tag["Inventory"].value if not matches(t)] for chunk in self.editor.level.getChunks(): @@ -1022,7 +1020,6 @@ def rightClickDown(self, evt): self.toggleMouseLook() def rightClickUp(self, evt): - x, y = evt.pos if self.rightMouseDragStart is None: return @@ -1139,7 +1136,7 @@ def sensitivityAdjust(d): # self.oldMousePosition = (x, y) # if (self.startingMousePosition[0] - x > adjustLimit or self.startingMousePosition[1] - y > adjustLimit or # self.startingMousePosition[0] - x < -adjustLimit or self.startingMousePosition[1] - y < -adjustLimit): - # mouse.set_pos(*self.startingMousePosition) + # mouse.set_pos(*self.startingMousePosition) # event.get(MOUSEMOTION) # self.oldMousePosition = (self.startingMousePosition) @@ -1174,7 +1171,8 @@ def updateFloorQuad(self): def drawFloorQuad(self): self.floorQuadList.call(self._drawFloorQuad) - def _drawCeiling(self): + @staticmethod + def _drawCeiling(): lines = [] minz = minx = -256 maxz = maxx = 256 @@ -1257,7 +1255,8 @@ def drawSkyBackground(self): self.skyList = glutils.DisplayList() self.skyList.call(self._drawSkyBackground) - def _drawSkyBackground(self): + @staticmethod + def _drawSkyBackground(): GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPushMatrix() GL.glLoadIdentity() @@ -1313,7 +1312,8 @@ def enableFog(self): GL.glFogf(GL.GL_FOG_DENSITY, 0.002) - def disableFog(self): + @staticmethod + def disableFog(): GL.glDisable(GL.GL_FOG) def getCameraPoint(self):