Ejemplo n.º 1
0
def get_item(item_or_block_id):
    """
    Get the Block or Item with the specified id, which must either be an instance
    of BlockID, or a string format BlockID knows how to parse.
    :type item_or_block_id: Union[BlockID, int]
    """
    if not isinstance(item_or_block_id, BlockID):
        item_or_block_id = BlockID(str(item_or_block_id))
    if item_or_block_id.is_item():
        return G.ITEMS_DIR[item_or_block_id]
    else:
        return G.BLOCKS_DIR[item_or_block_id]
Ejemplo n.º 2
0
def get_item(item_or_block_id):
    """
    Get the Block or Item with the specified id, which must either be an instance
    of BlockID, or a string format BlockID knows how to parse.
    :type item_or_block_id: Union[BlockID, int]
    """
    if not isinstance(item_or_block_id, BlockID):
        item_or_block_id = BlockID(str(item_or_block_id))
    if item_or_block_id.is_item():
        return G.ITEMS_DIR[item_or_block_id]
    else:
        return G.BLOCKS_DIR[item_or_block_id]
Ejemplo n.º 3
0
 def __init__(self, type = 0, amount = 1, durability = -1):
     if amount < 1:
         amount = 1
     self.type = BlockID(type, 0, get_item(type).icon_name)
     self.amount = amount
     if durability == -1:
         self.durability = -1 if not hasattr(self.get_object(), 'durability') else self.get_object().durability
     else:
         self.durability = durability
     self.max_durability = get_item(type).durability if hasattr(get_item(type), 'durability') else -1
     self.max_stack_size = get_item(type).max_stack_size
Ejemplo n.º 4
0
 def execute(self, block_id, amount=1, *args, **kwargs):
     try:
         bid = BlockID(block_id)
         item_or_block = get_item(float("%s.%s" % (bid.main, bid.sub)))
         self.send_info("Giving %s of '%s'." % (amount, item_or_block.name))
         self.user.inventory.add_item(bid, quantity=int(amount))
         #self.controller.item_list.update_items()
         #self.controller.inventory_list.update_items()
     except KeyError:
         raise CommandException(self.command_text, message="ID %s unknown." % block_id)
     except ValueError:
         raise CommandException(self.command_text, message="ID should be a number. Amount must be an integer.")
Ejemplo n.º 5
0
    def execute(self, x, y, z, block_id):
        bid = BlockID(block_id)
        try:
            item_or_block = get_item(float("%s.%s" % (bid.main, bid.sub)))
        except KeyError:
            raise CommandException(self.command_text, message="ID %s unknown." % block_id)
        except ValueError:
            raise CommandException(self.command_text, message="ID should be a number. Amount must be an integer.")

        if issubclass(type(item_or_block), Block):
            block = item_or_block
            try:
                self.world.add_block((int(x), int(y), int(z)), block)
            except ValueError:
                raise CommandException(self.command_text, message="Invalid coordinates must be integers")
        else:
            raise CommandException(
                self.command_text,
                message="Invalid value for block, expected Block not %s" % type(item_or_block).__name__)
Ejemplo n.º 6
0
 def dequeue_packet(self):
     with self.lock:
         packetid, packet = self.world.sector_packets.popleft()
     if packetid == 1:  # Entire Sector
         blocks, sectors = self.world, self.world.sectors
         secpos = struct.unpack("iii", packet[:12])
         sector = sectors[secpos]
         cx, cy, cz = sector_to_blockpos(secpos)
         fpos = 12
         exposed_pos = fpos + 1024
         for x in range(cx, cx + 8):
             for y in range(cy, cy + 8):
                 for z in range(cz, cz + 8):
                     read = packet[fpos:fpos + 2]
                     fpos += 2
                     unpacked = structuchar2.unpack(read)
                     if read != null2 and unpacked in BLOCKS_DIR:
                         position = x, y, z
                         try:
                             blocks[position] = BLOCKS_DIR[unpacked]
                             if blocks[position].sub_id_as_metadata:
                                 blocks[position] = type(
                                     BLOCKS_DIR[unpacked])()
                                 blocks[position].set_metadata(0)
                         except KeyError:
                             main_blk = BLOCKS_DIR[(unpacked[0], 0)]
                             if main_blk.sub_id_as_metadata:  # sub id is metadata
                                 blocks[position] = type(main_blk)()
                                 blocks[position].set_metadata(unpacked[-1])
                         sector.append(position)
                         if packet[exposed_pos:exposed_pos + 1] == b"1":
                             blocks.show_block(position)
                     exposed_pos += 1
         if secpos in self.world.sector_queue:
             del self.world.sector_queue[
                 secpos]  #Delete any hide sector orders
     elif packetid == 2:  # Blank Sector
         self.world.sectors[struct.unpack("iii", packet)] = []
     elif packetid == 3:  # Add Block
         self.world._add_block(struct.unpack("iii", packet[:12]),
                               BLOCKS_DIR[struct.unpack("BB", packet[12:])])
     elif packetid == 4:  # Remove Block
         self.world._remove_block(struct.unpack("iii", packet))
     elif packetid == 5:  # Chat Print
         self.controller.write_line(packet[:-4].decode('utf-8'),
                                    color=struct.unpack(
                                        "BBBB", packet[-4:]))
         if not self.controller.text_input.visible:
             self.controller.chat_box.visible = True
             pyglet.clock.unschedule(self.controller.hide_chat_box)
             pyglet.clock.schedule_once(self.controller.hide_chat_box,
                                        G.CHAT_FADE_TIME)
     elif packetid == 6:  # Inventory
         player = self.controller.player
         caret = 0
         for inventory in (player.quick_slots.slots, player.inventory.slots,
                           player.armor.slots):
             for i in range(len(inventory)):
                 id_main, id_sub, amount = struct.unpack(
                     "HBB", packet[caret:caret + 4])
                 caret += 4
                 if id_main == 0: continue
                 durability = -1
                 if id_main >= G.ITEM_ID_MIN and (
                         id_main, id_sub) not in G.ITEMS_DIR:
                     #The subid must be durability
                     durability = id_sub * G.ITEMS_DIR[
                         (id_main, 0)].durability // 255
                     id_sub = 0
                 inventory[i] = ItemStack(type=BlockID(id_main, id_sub),
                                          amount=amount,
                                          durability=durability)
         self.controller.item_list.update_items()
         self.controller.inventory_list.update_items()
     elif packetid == 7:  # New player connected
         plyid, name = struct.unpack(
             "H", packet[:2])[0], packet[2:].decode('utf-8')
         if plyid not in self.controller.player_ids:
             self.controller.player_ids[plyid] = Player(username=name,
                                                        local_player=False)
         elif name == '\0':
             del self.controller.player_ids[plyid]
     elif packetid == 8:  # Player Movement
         ply = self.controller.player_ids[struct.unpack("H", packet[:2])[0]]
         ply.momentum = struct.unpack("fff", packet[2:14])
         ply.position = struct.unpack("ddd", packet[14:])
     elif packetid == 9:  # Player Jump
         self.controller.player_ids[struct.unpack("H",
                                                  packet)[0]].dy = 0.016
     elif packetid == 10:  # Update Tile Entity
         self.world[struct.unpack("iii", packet[:12])].update_tile_entity(
             packet[12:])
     elif packetid == 255:  # Spawn Position
         self.controller.player.position = struct.unpack("iii", packet[:12])
         packet = packet[12:]
         packet, seed = extract_string_packet(packet)
         self.world.biome_generator = BiomeGenerator(seed)
         #Now that we know where the player should be, we can enable .update again
         self.controller.update = self.controller.update_disabled
     else:
         warn(
             "Received unknown packetid %s, there's probably a version mismatch between client and server!"
             % packetid)
Ejemplo n.º 7
0
    def dequeue_packet(self):
        with self.lock:
            packetid, packet = self.world.sector_packets.popleft()
        # print(f"CLIENTPACKET_ID: ", packetid) if packetid != 1 else None
        # print(f"CLIENTPACKET_PAK:", packet) if packetid != 1 else None
        if packetid == 1:  # Entire Sector
            blocks, sectors = self.world, self.world.sectors
            # secpos = struct.unpack("iii", packet[:12])
            secpos = packet["sector"]
            # print(packet)
            sector = sectors[secpos]
            cx, cy, cz = sector_to_blockpos(secpos)
            fpos = 0  # 12
            exposed_pos = 0  # fpos + 1024
            for x in range(cx, cx + 8):
                for y in range(cy, cy + 8):
                    for z in range(cz, cz + 8):
                        sector_data = packet["sectorData"][
                            fpos:fpos + 2]  # .encode("ascii")
                        # print(read)
                        fpos += 2
                        unpacked = structuchar2.unpack(sector_data)
                        # unpacked = read
                        # print("UNPACKED:", unpacked)
                        if sector_data != null2 and unpacked in BLOCKS_DIR:
                            position = x, y, z
                            try:
                                blocks[position] = BLOCKS_DIR[unpacked]
                                if blocks[position].sub_id_as_metadata:
                                    blocks[position] = type(
                                        BLOCKS_DIR[unpacked])()
                                    blocks[position].set_metadata(0)
                            except KeyError:
                                main_blk = BLOCKS_DIR[(unpacked[0], 0)]
                                if main_blk.sub_id_as_metadata:  # sub id is metadata
                                    blocks[position] = type(main_blk)()
                                    blocks[position].set_metadata(unpacked[-1])
                            sector.append(position)
                            if packet["exposedSector"][exposed_pos] is "1":
                                blocks.show_block(position)
                        exposed_pos += 1
            if secpos in self.world.sector_queue:
                del self.world.sector_queue[
                    secpos]  # Delete any hide sector orders
        elif packetid == 2:  # Blank Sector
            self.world.sectors[packet["sector"]] = []
        elif packetid == 3:  # Add Block
            self.world._add_block(packet["position"],
                                  BLOCKS_DIR[packet["block"]])
        elif packetid == 4:  # Remove Block
            self.world._remove_block(packet["position"])
        elif packetid == 5:  # Chat Print
            self.controller.write_line(packet["message"].decode('utf-8'),
                                       color=packet["color"])
            if not self.controller.text_input.visible:
                self.controller.chat_box.visible = True
                pyglet.clock.unschedule(self.controller.hide_chat_box)
                pyglet.clock.schedule_once(self.controller.hide_chat_box,
                                           G.CHAT_FADE_TIME)
        elif packetid == 6:  # Inventory
            player = self.controller.player
            caret = 0
            print("CLIENT_PACKET06:", packet)
            for i in range(len(player.quick_slots.slots)):
                id_main, id_sub, amount = packet["items"]["quickSlots"][i]

                # print(id_main, id_sub, amount)
                # caret += 4
                if id_main == 0: continue
                durability = -1
                if id_main >= G.ITEM_ID_MIN and (id_main,
                                                 id_sub) not in G.ITEMS_DIR:
                    # The subid must be durability
                    durability = id_sub * G.ITEMS_DIR[BlockID(
                        id_main, 0)].durability / 255
                    id_sub = 0
                player.quick_slots.slots[i] = ItemStack(type=BlockID(
                    id_main, id_sub),
                                                        amount=amount,
                                                        durability=durability)

            for i in range(len(player.inventory.slots)):
                id_main, id_sub, amount = packet["items"]["inventory"][i]

                # print(id_main, id_sub, amount)
                # caret += 4
                if id_main == 0: continue
                durability = -1
                if id_main >= G.ITEM_ID_MIN and (id_main,
                                                 id_sub) not in G.ITEMS_DIR:
                    # The subid must be durability
                    durability = id_sub * G.ITEMS_DIR[BlockID(
                        id_main, 0)].durability / 255
                    id_sub = 0
                player.quick_slots.slots[i] = ItemStack(type=BlockID(
                    id_main, id_sub),
                                                        amount=amount,
                                                        durability=durability)

            for i in range(len(player.armor.slots)):
                id_main, id_sub, amount = packet["items"]["armor"][i]

                # print(id_main, id_sub, amount)
                # caret += 4
                if id_main == 0: continue
                durability = -1
                if id_main >= G.ITEM_ID_MIN and (id_main,
                                                 id_sub) not in G.ITEMS_DIR:
                    # The subid must be durability
                    durability = id_sub * G.ITEMS_DIR[BlockID(
                        id_main, 0)].durability / 255
                    id_sub = 0
                player.quick_slots.slots[i] = ItemStack(type=BlockID(
                    id_main, id_sub),
                                                        amount=amount,
                                                        durability=durability)

            # for inventory in (player.quick_slots.slots, player.inventory.slots, player.armor.slots):
            #     # for item in (player.quick_slots.slots + player.inventory.slots + player.armor.slots)
            #     for i in range(len(inventory)):
            #         # print(packet)
            #
            #         # print("PACKET_0x06:", packet.decode())
            #
            #         # packet = eval(packet.decode()[:-1]) if packet.decode().startswith(
            #         #     "b'") and packet.decode().endswith("'" + chr(packet[-1])) else packet
            #         id_main, id_sub, amount = packet[]
            #
            #         # print(id_main, id_sub, amount)
            #         caret += 4
            #         if id_main == 0: continue
            #         durability = -1
            #         if id_main >= G.ITEM_ID_MIN and (id_main, id_sub) not in G.ITEMS_DIR:
            #             # The subid must be durability
            #             durability = id_sub * G.ITEMS_DIR[BlockID(id_main, 0)].durability / 255
            #             id_sub = 0
            #         inventory[i] = ItemStack(type=BlockID(id_main, id_sub), amount=amount, durability=durability)
            self.controller.item_list.update_items()
            self.controller.inventory_list.update_items()
        elif packetid == 7:  # New player connected
            # plyid, name = struct.unpack("H", packet[:2])[0], packet[2:].decode('utf-8')
            plyid = packet["playerID"]
            name = packet["username"]
            if plyid not in self.controller.player_ids:
                self.controller.player_ids[plyid] = Player(username=name,
                                                           local_player=False)
            elif name == '\0':
                del self.controller.player_ids[plyid]
        elif packetid == 8:  # Player Movement
            ply = self.controller.player_ids[
                packet["playerID"]]  # struct.unpack("H", packet[:2])[0]]
            ply.momentum = packet[
                "momentum"]  # struct.unpack("fff", packet[2:14])
            ply.position = packet[
                "position"]  # struct.unpack("ddd", packet[14:])
        elif packetid == 9:  # Player Jump
            self.controller.player_ids[packet["playerID"]].dy = 0.016
        elif packetid == 10:  # Update Tile Entity
            self.world[packet["position"]].update_tile_entity(packet["value"])
        elif packetid == 255:  # Spawn Position
            self.controller.player.position = packet[
                "position"]  # struct.unpack("iii", packet[:12])
            # print(packet)
            # packet = packet[12:]  # TODO: Get the packet data from dictionary. PACKETID: 255 | CLIENT
            # packet, seed = extract_string_packet(packet)
            seed = packet["seed"]
            self.world.biome_generator = BiomeGenerator(seed)
            # Now that we know where the player should be, we can enable .update again
            self.controller.update = self.controller.update_disabled
        else:
            warn(
                "Received unknown packetid %s, there's probably a version mismatch between client and server!"
                % packetid)
Ejemplo n.º 8
0
 def __init__(self):
     self.id = BlockID(self.id, 0, self.icon_name)
     G.ITEMS_DIR[self.id] = self
Ejemplo n.º 9
0
    'sector_to_offset',
    'save_world',
    'world_exists',
    'remove_world',
    'sector_exists',
    'load_region',
)

structvec = struct.Struct("hhh")
structushort = struct.Struct("H")
structuchar2 = struct.Struct("BB")
structvecBB = struct.Struct("hhhBB")

null2 = struct.pack("xx")  #Two \0's
null1024 = null2 * 512  #1024 \0's
air = BlockID(0)


def sector_to_filename(secpos: iVector) -> str:
    x, y, z = secpos
    return "%i.%i.%i.pyr" % (x // 4, y // 4, z // 4)


def region_to_filename(region: iVector) -> str:
    return "%i.%i.%i.pyr" % region


def sector_to_region(secpos: iVector) -> iVector:
    x, y, z = secpos
    return (x // 4, y // 4, z // 4)