예제 #1
0
def add_crash():
    log.printMSG("THE GAME CRASHED!!!")
    traceback.print_exc()
    try:
        _add_text("####################################")
        _add_text("the game crashed")
        _add_text("\nwith the following mods:")
        _print_mods()
        _add_text("\n")
        add_traceback()
        _add_text("------------------------------------")
        _add_text(
            "you are looking at the informations about the crash. look above for the real crash"
        )
        add_header(head=False)
        _add_text("------------------------------------")
        _add_text("these is an redone of the log:")
        _add_text("++++++++++++++++++++++++++++++++++++")
        for e in log.CASH:
            _add_text(" ".join(e))
        _add_text("++++++++++++++++++++++++++++++++++++")
        _add_text("####################################")
    except:
        _add_text("????????????????????????????????????")
        _add_text("EXCEPTION DURING HANDLING EXCEPTION")
        add_traceback()
        _add_text("????????????????????????????????????")
def on_end(entry):
    """
    we know that this is stuff around blocks, but we need it to make shour we have all items registrated
    """
    import textures.util

    textures.util.resize_file(
        G.local + "/assets/minecraft/textures/missingtexture.png",
        (32, 32),
        G.local + "/assets/minecraft/textures/missingtexture.png",
    )
    for b in tuple(G.blockhandler.blocktable.values()):
        b = b.getName()
        if not G.blockhandler.blocktable[b].getName(
        ) in G.itemhandler.itemclasses:
            if G.blockhandler.blocktable[b].getItemFile(None):
                file = G.blockhandler.blocktable[b].getItemFile(None)
                block = b

                class MissingItem(G.itemclass):
                    def getName(self):
                        return block

                    def getTexturFile(self):
                        return file

                G.itemhandler.register(MissingItem)
            else:
                log.printMSG("[CHECK][ERROR] block " + str(b) +
                             " has no ITEM!!!")
                register_l_block(G.blockhandler.blocktable[b].getName())
    def generateBlocksFromChunkProvider(self, chunk):
        r = self.random
        chunkprovider = self.worldprovider.getChunkProviderFor(chunk)
        log.printMSG("[WORLDGEN][INFO] generating blocks...")
        i = 0
        m = len(chunkprovider.generationcache["blocks_main"])
        for e in chunkprovider.generationcache["blocks_main"].keys():
            G.model.add_block(e,
                              chunkprovider.generationcache["blocks_main"][e])
            if i != 0 and i % 10 == 0:
                print("\x1b[2K\r", end="")
                log.printMSG(
                    "[GENERATOR][INFO] added " + str(i) + " blocks. need " +
                    str(m - i) + " more",
                    end="",
                )
            i += 1

        for k in chunkprovider.generationcache["blocks"].keys():
            G.BlockGenerateTasks[k] = [
                chunkprovider.generationcache["blocks"][k]
            ]
        print("\x1b[2K\r", end="")
        chunkprovider.generationcache["blocks"] = {}
        chunkprovider.generationcache["blocks_main"] = {}
 def saveWorld(self, file):
     log.printMSG(
         "[SAVER][0.0.0][WARNING] version 0.0.0 is NOT supported. do this on your own risk"
     )
     if not os.path.isdir(file):
         os.makedirs(file)
     self.saveDim(G.player.dimension,
                  file + "/DIM" + str(G.player.dimension.id))
     playerdata = {
         "dim": G.player.dimension.id,
         "pos": G.window.position,
         "rot": G.window.rotation,
         "gamemode": G.player.gamemode,
         "flying": G.window.flying,
         "selectedinventoryslot": G.player.selectedinventoryslot,
     }
     with open(file + "/player.json", mode="w") as f:
         json.dump(playerdata, f)
     storagedata = {
         "version": self.getStorageVersion(),
         "gameversion": G.VERSION_ID,
         "gameversionanme": G.VERSION_NAME,
         "seed": G.seed,
     }
     with open(file + "/storage.json", mode="w") as f:
         json.dump(storagedata, f)
 def checkDependecies(self):
     flag = True
     for mod in self.mods.values():
         versions = mod.getMcPythonVersions()
         if versions != None:
             if type(versions) == str:
                 if (versions != G.VERSION_NAME and
                         not "--deactivateversionicompatibles" in sys.argv):
                     log.printMSG("[MODLOADER][ERROR] mod " + str(mod) +
                                  " is requiring mc version " +
                                  str(versions))
                     flag = False
             else:
                 if (not any([x == G.VERSION_NAME for x in versions]) and
                         not "--deactivateversionicompatibles" in sys.argv):
                     log.printMSG("[MODLOADER][ERROR] mod " + str(mod) +
                                  " is requiring one of mc versions " +
                                  str(versions))
                     flag = False
         for e in mod.getDependencies():
             if not e[0] in self.mods:
                 log.printMSG("[MODLOADER][ERROR] dependencie error: mod " +
                              str(mod) + " needs mod " + str(e[0]))
                 flag = False
             elif len(e) > 1:
                 if callable(e[1]):
                     f = e[1]()
                     if not f:
                         flag = False
                 else:
                     modd = self.mods[e[0]]
                     depend_min = e[1][0] if len(e) > 1 else (-1, -1, -1)
                     depend_max = (e[1][1] if len(e) > 1 and len(e[1]) > 1
                                   else modd.getVersion())
                     depend_func = e[2] if len(e) > 2 else None
                     version_modd = modd.getVersion()
                     if not (depend_min[0] <= version_modd[0] <=
                             depend_max[0] and depend_min[1] <=
                             version_modd[1] <= depend_max[1]
                             and depend_min[2] <= version_modd[2] <=
                             depend_max[2]) and (
                                 (depend_func and depend_func())
                                 or not depend_func):
                         log.printMSG(
                             "[MODLOADER][ERROR] depenencie error: mod " +
                             str(mod) + " needs mod " + str(e[0]) +
                             " in version range " +
                             str([depend_min, depend_max]) + ", but " +
                             str(version_modd) + " is loaded")
                         flag = False
                     if len(e) > 2:
                         f = e[2]()
                         if not f:
                             flag = False
     if not flag:
         log.printMSG(
             "[MODLOADER][ERROR] there were errors in mod initialisation phase. NOT beginning loading phase"
         )
         sys.exit(-1)
 def __init__(self, file, format="json"):
     if format == "old":
         self.data = _decodeOLD(file)
     elif format == "json":
         self.data = _decodeJSON(file)
     else:
         log.printMSG("[LANGUAGE][ERROR] can't load lang file " + str(file))
     G.eventhandler.call("game:registry:on_language_registered", self)
 def add_scoreboard(self, name, scoreboardtype, *args, **kwargs):
     if scoreboardtype not in self.scoreboardtypes:
         log.printMSG("[SCOREBOARDHANDLER][ERROR] type " +
                      str(scoreboardtype) + " is unknown")
         return
     self.scoreboards[name] = self.scoreboardtypes[scoreboardtype](name,
                                                                   *args,
                                                                   **kwargs)
예제 #8
0
 def saveWorld(self, file, version="latest"):
     if version == "latest":
         version = self.latest
     if not version in self.versions:
         log.printMSG("[WORLDSAVER][ERROR] version is not supported")
         return
     obj = self.versions[version]
     obj["saver"].saveWorld(file)
 def remove_scoreboard(self, name):
     if name not in self.scoreboards:
         log.printMSG(
             "[SCOREBOARDHANDLER][ERROR] can't remove scoreboard named " +
             str(name) + ". These scoreboard" + " is not created.")
         return
     self.scoreboards[name].delete()
     del self.scoreboards[name]
예제 #10
0
 def setState(self, name):
     if not name in self.states:
         log.printMSG("[STATEHANDLER][ERROR] can't access state named " +
                      str(name))
         return
     if self.active_state:
         self.active_state.deactivate()
     self.active_state = self.states[name]
     self.active_state.activate()
    def update(self, dt):
        """This method is scheduled to be called repeatedly by the pyglet
        clock.

        Parameters
        ----------
        dt : float
            The change in time since the last call.

        """
        G.model.process_queue()
        sector = mathhelper.sectorize(self.position)
        if (sector != self.sector
                and G.statehandler.active_state.getName() == "minecraft:game"):
            G.model.change_sectors(self.sector, sector)
            if self.sector is None:
                G.model.process_entire_queue()
            self.sector = sector
        m = 8
        dt = min(dt, 0.2)
        for _ in range(m):
            self._update(dt / m)
        for entity in G.entityhandler.entitys:
            entity.update(dt)
        G.eventhandler.call("core:update")
        if G.statehandler.active_state.getName() == "minecraft:game":
            self.time += dt * 20
            self.day += round(self.time // 24000)
            self.time = round(self.time % 24000)
        if G.GAMESTAGE != 3:
            return
        i = 0
        max = len(G.BlockGenerateTasks)
        l = list(G.BlockGenerateTasks.keys())
        t = time.time()
        for position in l:
            G.model.add_block(position,
                              G.BlockGenerateTasks[position][0],
                              immediate=True)
            task = G.BlockGenerateTasks[position]
            if len(task) > 1:
                task = task[1:]
                while len(task) > 0:
                    st = task.pop(0)
                    cx, _, cz = mathhelper.sectorize(position)
                    chunkprovider = (
                        G.player.dimension.worldprovider.getChunkProviderFor(
                            (cx, cz)))
                    if st == "sdata":
                        chunkprovider.world[position].setStorageData(
                            task.pop(0))
                    else:
                        log.printMSG("[TASKS][ERROR] unknown subtask " +
                                     str(st))
            del G.BlockGenerateTasks[position]
            if time.time() - t > 0.1:
                return
 def execute(self, command):
     splitted = command.split(" ")
     if len(command) > 0 and command[0] != "/":
         log.printMSG("[CHAT] " + command)
         return
     else:
         G.commandhandler.executeCommand(command, G.player.entity,
                                         G.window.position)
         return
예제 #13
0
 def __init__(self, name, *args, **kwargs):
     self.name = name
     if hasattr(self, "create"):
         self.create(*args, **kwargs)
     elif len(args) + len(kwargs) > 0:
         log.printMSG(
             "[SCOREBOARD][ERROR] getted arguments for scoreboard typed as "
             + str(type(self)) +
             " but it has no create-function for analysing it")
         return
 def addEventName(self, name, msg=True):
     """
     adds an new eventname
     :param name: the name of the event
     """
     if name in self.eventnames:
         if msg:
             log.printMSG("[EVENTHANDLER][ERROR] try to add event named " +
                          str(name) + ", but it is known")
         return
     self.eventnames[name] = []
 def saveDim(self, dim, file):
     if not os.path.isdir(file):
         os.makedirs(file)
     if dim != G.player.dimension:
         log.printMSG(
             "[WORLDSAVER][0.0.0][ERROR] can't save unloaded dim " +
             str(dim))
         return
     for cx, cz in G.player.dimension.worldprovider.chunkproviders.keys():
         self.saveChunk(cx, cz,
                        file + "/" + str(cx) + "." + str(cz) + ".chunk")
예제 #16
0
 def executeCommand(command, entity, position):
     splitted = command.split(" ")
     if len(splitted) > 1:
         d = G.local + "/saves/" + splitted[1]
     elif G.window.worldname:
         d = G.window.worldname
     else:
         log.printMSG("[COMMANDPARSER][SAVE][ERROR] unknown dirname")
         return
     G.window.worldname = d
     G.storagehandler.saveWorld(d)
 def searchForMods(self):
     # print(EVENTLIST, EVENTENTRYLIST)
     mods = self.getModDirs()
     self.loadMods(mods)
     self.checkDependecies()
     sorter = ModSorter.ModSorter(self.mods)
     sorter.sort()
     log.printMSG("[MODLOADER] we will load mods in the following order:")
     for mod in sorter.modlistsorted:
         log.printMSG("  :" + str(mod.getUserFriendlyName()))
     self.bind_events(sorter)
     self.call_events(sorter)
 def removeEvent(self, name):
     """
     remove an event
     :param name: the name of the event to remove
     """
     if not name in self.eventnames:
         log.printMSG(
             "[EVENTHANDLER][ERROR] try to remove an unknown event: " +
             str(name))
         return
     self.clearEvent(name)
     del self.eventnames[name]
 def remove_on_event(self, id):
     """
     unbinds an function to an event
     :param id: the id of the binding
     """
     if not id in self.functions:
         log.printMSG(
             "[EVENTHANDLER][ERROR] try to remove an unknown function " +
             str(id))
         return
     self.eventnames[self.functions[id][1]].remove(id)
     del self.functions[id]
 def clearEvent(self, name):
     """
     clear all functions to an event
     :param name: the name of the event to clear
     """
     if not name in self.eventnames:
         log.printMSG(
             "[EVENTHANDLER][ERROR] try to clear an unknown event: " +
             str(name))
         return
     for e in self.eventnames[name]:
         del self.functions[e]
     self.eventnames[name] = []
예제 #21
0
 def __init__(self, name, amount=1):
     self.update_func = None
     self.slot = None
     if type(name) == str:
         self.name = name
         item = G.itemhandler.getByName(name)
         if item:
             self.item = item()
             self.amount = amount
         else:
             log.printMSG("[IItemStack][ERROR] item unknown (named " +
                          str(name) + ")")
             self.item = None
             self.amount = 0
     elif type(name) == G.itemclass:
         self.name = name.getName()
         self.item = name
     elif name == None:
         self.name = None
         self.item = None
     else:
         log.printMSG("[IItemStack][ERROR] can't set item " + str(name))
         self.name = None
         self.item = None
     self.__amount = amount
     if self.item:
         textures.util.resize_file(self.item.getTexturFile(), (32, 32))
         self.image = pyglet.sprite.Sprite(
             pyglet.image.load(self.item.getTexturFile()))
         """texturslitcher.ImageAtlas.save_image(
             texturslitcher.ImageAtlas.resize(
                 texturslitcher.ImageAtlas.load_image(self.item.getTexturFile()),
                 (32, 32)
             ),
             self.item.getTexturFile()
         )
         texturslitcher.ImageAtlas.resize(image, (32, 32))
         texturslitcher.ImageAtlas.save_image(image, self.item.getTexturFile())
         #texturhandler.resize(self.item.getTexturFile(), (32, 32), self.item.getTexturFile())
         self.image = pyglet.sprite.Sprite(pyglet.image.load(self.item.getTexturFile()))"""
     else:
         self.image = None
     self.texturfile = self.item.getTexturFile() if self.item else None
     self.lable = pyglet.text.Label(
         "",
         font_name="Arial",
         font_size=10,
         anchor_x="left",
         anchor_y="top",
         color=(255, 255, 255, 255),
     )
 def hide_inventory(self, id):
     """hides the inventory"""
     if type(id) != int:
         id = id.id
     self.inventorys[id].active = False
     self.inventorys[id].on_hide()
     if id not in self.activeinventorys:
         log.printMSG("[ERROR]")
         return
     self.activeinventorys.remove(id)
     if type(self.inventorys[id]) == InventoryCollection:
         for e in self.activeated[id]:
             del self.activeated[id]
             self.hide_inventory(e)
예제 #23
0
    def _initialize(self, *args):
        """Initialize the world by placing all the blocks."""
        log.printMSG("[MAINTHREAD][WINDOW][MODEL][INFO] generating world...")
        import world.OverWorld

        G.dimensionhandler.register(world.OverWorld.OverWorld)

        G.dimensionhandler.dimensions[0].join()

        G.player.dimension = G.dimensionhandler.dimensions[0]

        G.dimensionhandler.prepare()

        G.GAMESTAGE = 3
        self.change_sectors(None, G.window.get_motion_vector())
 def saveChunk(self, cx, cz, file):
     if not (cx, cz) in G.player.dimension.worldprovider.chunkproviders:
         log.printMSG(
             "[WORLDSAVER][0.0.0][ERROR] can't save unloaded chunk " +
             str(cx, cz))
         return
     chunkdata = {}
     chunkprovider = G.player.dimension.worldprovider.getChunkProviderFor(
         (cx, cz))
     for position in chunkprovider.world.keys():
         block = chunkprovider.world[position]
         chunkdata[str(self._transformposition(
             cx, cz, *position))] = block.getStorageData()
     with open(file, mode="wb") as f:
         pickle.dump(chunkdata, f)
 def prepare(self):
     if not config.WorldGenerator.USED_DEBUG_GEN:
         for cx in range(*self.WORLDSIZE[0]):
             for cz in range(*self.WORLDSIZE[1]):
                 log.printMSG(
                     "[OVERWORLD][GENERATOR][INFO] generating chunk "
                     + str(cx)
                     + "|"
                     + str(cz)
                 )
                 self.worldprovider.generateChunkFor((cx, cz))
     else:
         self.worldprovider.generateChunkFor((0, 0))
         print(gen.DebugWorldGenerator.BLOCKTABLE.keys())
         for chunk in gen.DebugWorldGenerator.BLOCKTABLE.keys():
             self.worldprovider.generateChunkFor(chunk)
 def loadChunk(self, cx, cz, file):
     log.printMSG(cx, cz)
     with open(file, mode="rb") as f:
         chunkdata = pickle.load(f)
     mx, mz = int(cx), int(cz)
     for rpos in chunkdata.keys():
         x, y, z = rpos.split(",")
         x = int(x[1:])
         y = int(y[1:])
         z = int(z[1:-1])
         pos = (x + mx * 16, y, z + mz * 16)
         G.BlockGenerateTasks[pos] = [
             chunkdata[rpos]["name"],
             "sdata",
             chunkdata[rpos],
         ]
 def on_key_press(self, symbol, modifiers):
     G.window.strafe = [0, 0]
     if symbol in [65505]:
         return
     elif symbol == config.Keyboard.CLOSE:
         self.text = ""
         self.commandpointer = -1
         G.inventoryhandler.hide_inventory(self.id)
     elif symbol == config.Keyboard.RUN_COMMAND:
         self.execute(self.text)
         self.commandindex.insert(0, self.text)
         self.commandpointer = -1
         self.text = ""
         G.inventoryhandler.hide_inventory(self.id)
     elif symbol == 65288:
         self.text = self.text[:-1]
     elif symbol == 65507 and (modifiers & key.MOD_CTRL):
         clipboard.copy(self.text)
         return
     elif symbol == key.V and (modifiers & key.MOD_CTRL):
         self.text += clipboard.paste()
         return
     elif symbol == key.D and (modifiers & key.MOD_CTRL):
         self.text = ""
         return
     elif modifiers & key.MOD_SHIFT:
         if symbol in KEYDICT[1]:
             self.text += KEYDICT[1][symbol]
         else:
             log.printMSG("[CHAT][ERROR] can't interpet key " +
                          str(symbol) + " with SHIFT")
     elif modifiers & key.MOD_ALT:
         if symbol in KEYDICT[2]:
             self.text += KEYDICT[2][symbol]
         else:
             log.printMSG("[CHAT][ERROR] can't interpet key " +
                          str(symbol) + " with ALT")
     elif symbol in KEYDICT[0]:
         self.text += KEYDICT[0][symbol]
     elif symbol == key.TAB:
         log.printMSG("[CHAT][WARN] complet of commands are not supported")
     elif symbol == key.UP:
         if self.commandpointer + 1 < len(self.commandindex):
             self.commandpointer += 1
             self.text = self.commandindex[self.commandpointer]
     elif symbol == key.DOWN:
         if self.commandpointer > 0:
             self.commandpointer -= 1
             self.text = self.commandindex[self.commandpointer]
         elif self.commandpointer != -1:
             self.commandpointer = -1
     else:
         log.printMSG("[CHAT][ERROR] can't interpet key " + str(symbol) +
                      " with modifiers: " + str(modifiers))
     G.window.strafe = [0, 0]
예제 #28
0
 def check_inventory(self, inventory):
     if not issubclass(
         type(inventory), crafting.ICraftingInventory.ICraftingInventory
     ):
         log.printMSG(
             "[CRAFTINGHANDLER][INFO] can't check inventory "
             + str(inventory)
             + ". Inventory is not an crafting inventory"
         )
         return
     inventory.active_recipe = None
     for e in inventory.get_grid_names():
         for slotarray in inventory.get_slot_arrays(e):
             recipe = inventory.check_recipes(self.recipes[e], slotarray)
             if recipe:
                 inventory.set_output(inventory.get_output_for_recipe(recipe))
                 return
     inventory.clear_output()
 def __init__(self, file, format="old"):
     if format == "old":
         self.data = _decodeOLD(file)
     elif format == "json":
         self.data = _decodeJSON(file)
     else:
         log.printMSG("[LANGUAGE][ERROR] can't load lang extension file " +
                      str(file))
         self.data = {}
     self.name = file.split("/")[-1].split(".")[0]
     if hasattr(G.LANG, self.name):
         getattr(G.LANG, self.name)._applyExtenstion(self)
     else:
         setattr(
             G.LANG,
             file.split("/")[-1].split(".")[0],
             LanguageFile(file, format="old"),
         )
예제 #30
0
 def on_event(self, name, *args):
     if name == "opengl:draw2d":
         # G.window.set_size(1200, 620)
         G.window.set_exclusive_mouse(False)
         self.image1.draw()
         self.lable1.x = 90
         self.lable1.y = 3
         self.lable1.draw()
         self.lable2.x = 555
         self.lable2.y = 358
         self.lable2.draw()
         self.lable3.x = 550
         self.lable3.y = 318
         self.lable3.draw()
         self.lable4.x = 610
         self.lable4.y = 210
         self.lable4.draw()
     elif name == "core:window:on_mouse_press":
         x, y, button, mod = args
         if x >= 424 and y >= 348 and x <= 777 and y <= 381:
             G.window.flying = True
             G.window.position = (0, 4000, 0)
             G.dimensionhandler.generateclasses()
             G.player.dimension = G.dimensionhandler.dimensions[0]
             G.eventhandler.call("worldgen:newworld")
             G.window.time = 0
             G.window.day = 0
             chunk = (0, 0)
             x, y = random.randint(0, 15), random.randint(0, 15)
             x += chunk[0] * 16
             y += chunk[1] * 16
             G.window.position = (0, 255, 0)
             G.player.gamemode = 1
             G.window.flying = True
             G.SPAWNPOINT = G.window.position
             G.window.rotation = (0, 0)
             G.window.flying = False
             G.statehandler.setState("minecraft:game")
         elif x >= 550 and y >= 318 and x <= 777 and y <= 338:
             log.printMSG("[TITLESCREEN][ERROR] multiplayer is NOT arrival")
         elif x >= 605 and y >= 200 and x <= 777 and y <= 234:
             G.window.close()
         else:
             log.printMSG(args)