Esempio n. 1
0
    def newPlayer(self):
        playerTag = nbt.TAG_Compound()

        playerTag['Air'] = nbt.TAG_Short(300)
        playerTag['AttackTime'] = nbt.TAG_Short(0)
        playerTag['DeathTime'] = nbt.TAG_Short(0)
        playerTag['Fire'] = nbt.TAG_Short(-20)
        playerTag['Health'] = nbt.TAG_Short(20)
        playerTag['HurtTime'] = nbt.TAG_Short(0)
        playerTag['Score'] = nbt.TAG_Int(0)
        playerTag['FallDistance'] = nbt.TAG_Float(0)
        playerTag['OnGround'] = nbt.TAG_Byte(0)
        playerTag['Dimension'] = nbt.TAG_Int(self.editor.level.dimNo)

        playerTag["Inventory"] = nbt.TAG_List()

        playerTag['Motion'] = nbt.TAG_List([nbt.TAG_Double(0) for i in xrange(3)])
        spawn = self.level.playerSpawnPosition()
        spawnX = spawn[0]
        spawnZ = spawn[2]
        blocks = [self.level.blockAt(spawnX, i, spawnZ) for i in xrange(self.level.Height)]
        i = self.level.Height
        done = False
        for index, b in enumerate(reversed(blocks)):
            if b != 0 and not done:
                i = index
                done = True
        spawnY = self.level.Height - i
        playerTag['Pos'] = nbt.TAG_List([nbt.TAG_Double([spawnX, spawnY, spawnZ][i]) for i in xrange(3)])
        playerTag['Rotation'] = nbt.TAG_List([nbt.TAG_Float(0), nbt.TAG_Float(0)])

        return playerTag
Esempio n. 2
0
 def placespawners(self, level=0):
     self.pm.init(self.steps, label='Placing spawners:')
     count = self.steps
     for lm in self.landmarks:
         count -= 1
         self.pm.update_left(count)
         loc = lm.spawnerloc()
         if loc is None:
             continue
         loc = lm.offset + loc
         self.setblock(loc, materials.Spawner)
         entity = weighted_choice(cfg.master_landmark_mobs)
         root_tag = self.getspawnertags(entity)
         root_tag['id'] = nbt.TAG_String('MobSpawner')
         root_tag['x'] = nbt.TAG_Int(loc.x )
         root_tag['y'] = nbt.TAG_Int(loc.y )
         root_tag['z'] = nbt.TAG_Int(loc.z )
         root_tag['Delay'] = nbt.TAG_Short(0)
         SpawnCount = cfg.SpawnCount
         SpawnMaxNearbyEntities = cfg.SpawnMaxNearbyEntities
         SpawnMinDelay = cfg.SpawnMinDelay
         SpawnMaxDelay = cfg.SpawnMaxDelay
         SpawnRequiredPlayerRange = cfg.SpawnRequiredPlayerRange
         # But don't overwrite tags from NBT files
         if (SpawnCount != 0):
             try:
                 root_tag['SpawnCount']
             except:
                 root_tag['SpawnCount'] = nbt.TAG_Short(SpawnCount)
         if (SpawnMaxNearbyEntities != 0):
             try:
                 root_tag['MaxNearbyEntities']
             except:
                 root_tag['MaxNearbyEntities'] = nbt.TAG_Short(
                     SpawnMaxNearbyEntities)
         if (SpawnMinDelay != 0):
             try:
                 root_tag['MinSpawnDelay']
             except:
                 root_tag['MinSpawnDelay'] = nbt.TAG_Short(SpawnMinDelay)
         if (SpawnMaxDelay != 0):
             try:
                 root_tag['MaxSpawnDelay']
             except:
                 root_tag['MaxSpawnDelay'] = nbt.TAG_Short(SpawnMaxDelay)
         if (SpawnRequiredPlayerRange != 0):
             try:
                 root_tag['RequiredPlayerRange']
             except:
                 root_tag['RequiredPlayerRange'] = nbt.TAG_Short(
                     SpawnRequiredPlayerRange)
         # Finally give the tag to the entity
         self.tile_ents[loc] = root_tag
     self.pm.set_complete()
Esempio n. 3
0
    def saveLastPosition(self, mainViewport, dimension):
        '''
        Saves the final position of the camera viewport when the world is closed or MCEdit is exited
        
        :param mainViewport: The reference to viewport object
        :param dimension: The dimension the camera viewport is currently in
        :type dimension: int
        '''
        log.info('Saving last position.')
        if "LastPosition" in self.nbt_waypoints:
            del self.nbt_waypoints["LastPosition"]
        topTag = nbt.TAG_Compound()
        topTag["Dimension"] = nbt.TAG_Int(dimension)

        pos = nbt.TAG_List()
        pos.append(nbt.TAG_Float(mainViewport.cameraPosition[0]))
        pos.append(nbt.TAG_Float(mainViewport.cameraPosition[1]))
        pos.append(nbt.TAG_Float(mainViewport.cameraPosition[2]))
        topTag["Coordinates"] = pos

        rot = nbt.TAG_List()
        rot.append(nbt.TAG_Float(mainViewport.yaw))
        rot.append(nbt.TAG_Float(mainViewport.pitch))
        topTag["Rotation"] = rot

        self.nbt_waypoints["LastPosition"] = topTag
        self.save()
Esempio n. 4
0
def convert(tag):
    out = None
    if (tag.type is parse.TAG_Byte):
        out = nbt.TAG_Byte(value=tag.data, name=tag.name)
    elif (tag.type is parse.TAG_Byte_Array):
        out = nbt.TAG_Byte_Array(value=fromstring(tag.data), name=tag.name)
    elif (tag.type is parse.TAG_Double):
        out = nbt.TAG_Double(value=tag.data, name=tag.name)
    elif (tag.type is parse.TAG_Float):
        out = nbt.TAG_Float(value=tag.data, name=tag.name)
    elif (tag.type is parse.TAG_Int):
        out = nbt.TAG_Int(value=tag.data, name=tag.name)
    elif (tag.type is parse.TAG_Int_Array):
        out = nbt.TAG_Int_Array(value=tag.data, name=tag.name)
    elif (tag.type is parse.TAG_Long):
        out = nbt.TAG_Long(value=tag.data, name=tag.name)
    elif (tag.type is parse.TAG_Short):
        out = nbt.TAG_Short(value=tag.data, name=tag.name)
    elif (tag.type is parse.TAG_String):
        out = nbt.TAG_String(value=tag.data, name=tag.name)
    # Recursives
    elif (tag.type is parse.TAG_Compound):
        out = nbt.TAG_Compound(name=tag.name)
        for item in tag.data:
            temp = convert(item)
            if (temp is not None):
                out[temp.name] = temp
    elif (tag.type is parse.TAG_List):
        out = nbt.TAG_List(name=tag.name)
        for item in tag.data[1]:
            temp = convert(dummyNBTyaml(tag.data[0], item))
            if (temp is not None):
                out.append(temp)

    return out
Esempio n. 5
0
 def save(self):
     '''
     Saves all waypoint information to the 'mcedit_waypoints.dat' file in the world directory
     '''
     if DEBUG:
         current_frame = inspect.currentframe()
         outerframe = inspect.getouterframes(current_frame, 2)[1]
         print "Called by '" + str(outerframe[3]) + "()' in '" + str(
             outerframe[1].split("\\")[-1]) + "' at line " + str(
                 outerframe[2])
     del self.nbt_waypoints["Waypoints"]
     self.nbt_waypoints["Waypoints"] = nbt.TAG_List()
     for waypoint in self.waypoints.keys():
         if waypoint.split()[0] == "Empty":
             continue
         way = nbt.TAG_Compound()
         way["Name"] = nbt.TAG_String(waypoint.split()[0])
         way["Dimension"] = nbt.TAG_Int(self.waypoints[waypoint][5])
         coords = nbt.TAG_List()
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][0]))
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][1]))
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][2]))
         rot = nbt.TAG_List()
         rot.append(nbt.TAG_Float(self.waypoints[waypoint][3]))
         rot.append(nbt.TAG_Float(self.waypoints[waypoint][4]))
         way["Coordinates"] = coords
         way["Rotation"] = rot
         self.nbt_waypoints["Waypoints"].append(way)
     self.nbt_waypoints.save(
         os.path.join(self.worldDirectory, u"mcedit_waypoints.dat"))
Esempio n. 6
0
    def loadrandbooktext(self):
        item = nbt.TAG_Compound()
        item['id'] = nbt.TAG_String('minecraft:written_book')
        # No books? Give a book and quill instead
        if len(self.booklist) == 0:
            item['id'] = nbt.TAG_String('minecraft:writable_book')
            return item
        # Open the book's text file
        bookfile = open(os.path.join(self.book_path, random.choice(self.booklist)))
        bookdata = bookfile.read().splitlines()
        bookfile.close()
        # Create NBT tag
        item['tag'] = nbt.TAG_Compound()
        # Prevent unusual characters from being used with filter
        item['tag']['author'] = nbt.TAG_String(
            filter(
                lambda x: x in self.valid_characters,
                bookdata.pop(0)))
        title = filter(lambda x: x in self.valid_characters,bookdata.pop(0))
        item['tag']['title'] = nbt.TAG_String(title[:32])
        item['tag']["pages"] = nbt.TAG_List()
        # Slice the pages at 50 and the page text at 256 to match minecraft
        # limits
        for p in bookdata[:50]:
            page = filter(lambda x: x in self.valid_characters, p)
            item['tag']["pages"].append(nbt.TAG_String(encodeJSONtext(page[:256])))
        # Give the book an edition
        ed = topheavy_random(0, 9)
        item['tag']['display'] = nbt.TAG_Compound()
        item['tag']['display']['Lore'] = nbt.TAG_List()
        item['tag']['display']['Lore'].append(
            nbt.TAG_String(
                converttoordinal(ed+1) +
                ' Edition'))
        if (ed == 0):
            item['tag']['generation'] = nbt.TAG_Int(0)
        elif (ed == 1):
            item['tag']['generation'] = nbt.TAG_Int(1)
        else:
            item['tag']['generation'] = nbt.TAG_Int(2)

        return item
Esempio n. 7
0
    def loadrandbooktext(self):
        item = nbt.TAG_Compound()
        item['id'] = nbt.TAG_Short(387)
        # No books? Give a book and quill instead
        if len(self.booklist) == 0:
            item['id'] = nbt.TAG_Short(386)
            return item
        # Open the book's text file
        bookfile = open(
            os.path.join(self.book_path, random.choice(self.booklist)))
        bookdata = bookfile.read().splitlines()
        bookfile.close()
        # Create NBT tag
        item['tag'] = nbt.TAG_Compound()
        item['tag']['author'] = nbt.TAG_String(
            filter(lambda x: x in self.valid_characters, bookdata.pop(0)))
        # Prevent unusual characters from being used
        item['tag']['title'] = nbt.TAG_String(
            filter(lambda x: x in self.valid_characters, bookdata.pop(0)))
        item['tag']["pages"] = nbt.TAG_List()
        # Slice the pages at 50 and the page text at 256 to match minecraft
        # limits
        for p in bookdata[:50]:
            page = filter(lambda x: x in self.valid_characters, p)
            page = self.ConvertEscapeChars(page)
            # Escape quote charcaters
            page = page.replace('"', '\\"')
            item['tag']["pages"].append(nbt.TAG_String('"%s"' % (page[:256])))
        # Give the book an edition
        ed = topheavy_random(0, 9)
        item['tag']['display'] = nbt.TAG_Compound()
        item['tag']['display']['Lore'] = nbt.TAG_List()
        item['tag']['display']['Lore'].append(
            nbt.TAG_String(self.ed_dict[ed] + ' Edition'))
        if (ed == 0):
            item['tag']['generation'] = nbt.TAG_Int(0)
        elif (ed == 1):
            item['tag']['generation'] = nbt.TAG_Int(1)
        else:
            item['tag']['generation'] = nbt.TAG_Int(2)

        return item
Esempio n. 8
0
    def render(self):
        center = self.pos + Vec(8, 0, 8)
        size = random.randint(6, 10)

        # Now need to flatten the circle in case it is on a slope
        # find ground type at centre, and change all heights within circle
        # to be the same, and the same ground type
        # center is ground level.
        self.addclearing(center, size)

        # Create the circle of skulls
        p0 = Vec(center.x - size / 2 + 1 - self.parent.position.x,
                 self.parent.position.y - center.y,
                 center.z - size / 2 + 1 - self.parent.position.z)
        p1 = p0.trans(size - 1, 0, size - 1)
        skulls = (
            (0, 100),  # Plain Skull
            (1, 5),  # Wither Skull
            (3, 1),  # Steve Head
        )
        counter = 0
        for p in iterate_ellipse(p0, p1):
            if ((p.x + p.z) % 2 == 0):
                self.parent.setblock(p.up(1), materials.Fence)
                # Abort if there is no skull here
                if (random.randint(0, 100) < 33):
                    continue
                SkullType = weighted_choice(skulls)
                self.parent.setblock(p.up(2), materials.MobHead, 1)
                root_tag = nbt.TAG_Compound()
                root_tag['id'] = nbt.TAG_String('Skull')
                root_tag['x'] = nbt.TAG_Int(p.x)
                root_tag['y'] = nbt.TAG_Int(p.y - 2)
                root_tag['z'] = nbt.TAG_Int(p.z)
                root_tag['SkullType'] = nbt.TAG_Byte(SkullType)
                root_tag['Rot'] = nbt.TAG_Byte(random.randint(0, 15))
                self.parent.tile_ents[p.up(2)] = root_tag
            elif (random.randint(0, 100) < 10):
                self.parent.setblock(p.up(1), materials.Torch)
Esempio n. 9
0
def parse_nbt(node, params={}):
    """Recursivly build nbt datastructure from xml."""

    if 'name' in node.attrib:
        name = node.attrib['name']
    else:
        name = ''

    if node.text and node.text != '':
        text = replace_params(node.text, params)
    else:
        text = ''

    if node.tag == 'Compound':
        values = [] # list of other tags
        for child in node:
            values.append(parse_nbt(child, params))
        return nbt.TAG_Compound(values, name)

    if node.tag == 'List':
        values = [] # list of other tags
        for child in node:
            values.append(parse_nbt(child, params))
        return nbt.TAG_List(values, name)

    elif node.tag == 'String':
        return nbt.TAG_String(text, name)

    elif node.tag == 'Int':
        return nbt.TAG_Int(text, name)

    elif node.tag == 'Byte':
        return nbt.TAG_Byte(text, name)

    elif node.tag == 'Short':
        return nbt.TAG_Short(text, name)

    elif node.tag == 'Long':
        return nbt.TAG_Long(text, name)

    elif node.tag == 'Float':
        return nbt.TAG_Float(text, name)

    elif node.tag == 'Double':
        return nbt.TAG_Double(text, name)

    else:
        raise 'Unsupported'
Esempio n. 10
0
    def add_painting(self, painting_file):
        src = os.path.join(self.painting_path, painting_file + '.dat')
        painting_file_hash = hashlib.md5(open(src, 'r').read()).digest()
        # Look up file in hashtable
        if painting_file_hash in self.maphash:
            mapid = self.maphash[painting_file_hash]
        else:
            # Initialize the map count if it doesn't exist.
            if 'map' not in self.idcounts:
                self.idcounts['map'] = nbt.TAG_Short(-1)
            # Increment and return id
            self.idcounts['map'].value += 1
            mapid = self.idcounts['map'].value
            # Copy the map to the data dir
            dest = os.path.join(self.mapstore, 'map_%d.dat' % (mapid))
            try:
                shutil.copy(src, dest)
            except:
                sys.exit('Error when placing painting in map directory.')
            self.maphash[painting_file_hash] = mapid  # Update hashtable
            self.update_mapstore()

        # Create map item tag
        item = nbt.TAG_Compound()
        item['id'] = nbt.TAG_String(items.byName('map').id)
        item['Damage'] = nbt.TAG_Short(mapid)
        item['Count'] = nbt.TAG_Byte(1)

        # Fetch the lore text for this map
        lorefile = open(
            os.path.join(self.painting_path, painting_file + '.txt'))
        loredata = lorefile.read().splitlines()
        lorefile.close()
        # Create display tags
        valid_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ "
        item['tag'] = nbt.TAG_Compound()
        item['tag']['display'] = nbt.TAG_Compound()
        item['tag']['display']['Name'] = nbt.TAG_String(
            filter(lambda x: x in valid_characters, loredata.pop(0)))
        item['tag']['display']['Lore'] = nbt.TAG_List()
        # Slice at 5 lines of 50 chars each
        for p in loredata[:5]:
            line = filter(lambda x: x in valid_characters, p)
            item['tag']['display']['Lore'].append(nbt.TAG_String(line[:50]))
        item['tag']['display']['MapColor'] = nbt.TAG_Int(self.paintingcolor)

        return item
Esempio n. 11
0
 def save(self):
     del self.nbt_waypoints["Waypoints"]
     self.nbt_waypoints["Waypoints"] = nbt.TAG_List()
     for waypoint in self.waypoints.keys():
         way = nbt.TAG_Compound()
         way["Name"] = nbt.TAG_String(waypoint.split()[0])
         way["Dimension"] = nbt.TAG_Int(self.waypoints[waypoint][5])
         coords = nbt.TAG_List()
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][0]))
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][1]))
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][2]))
         rot = nbt.TAG_List()
         rot.append(nbt.TAG_Float(self.waypoints[waypoint][3]))
         rot.append(nbt.TAG_Float(self.waypoints[waypoint][4]))
         way["Coordinates"] = coords
         way["Rotation"] = rot
         self.nbt_waypoints["Waypoints"].append(way)
     self.nbt_waypoints.save(os.path.join(self.worldDirectory, u"mcedit_waypoints.dat"))
Esempio n. 12
0
 def saveLastPosition(self, mainViewport, dimension):
     if "LastPosition" in self.nbt_waypoints:
         del self.nbt_waypoints["LastPosition"]
     topTag = nbt.TAG_Compound()
     topTag["Dimension"] = nbt.TAG_Int(dimension)
     
     pos = nbt.TAG_List()
     pos.append(nbt.TAG_Float(mainViewport.cameraPosition[0]))
     pos.append(nbt.TAG_Float(mainViewport.cameraPosition[1]))
     pos.append(nbt.TAG_Float(mainViewport.cameraPosition[2]))
     topTag["Coordinates"] = pos
     
     rot = nbt.TAG_List()
     rot.append(nbt.TAG_Float(mainViewport.yaw))
     rot.append(nbt.TAG_Float(mainViewport.pitch))
     topTag["Rotation"] = rot
     
     self.nbt_waypoints["LastPosition"] = topTag
     self.save()
     
Esempio n. 13
0
 def save(self):
     '''
     Saves all waypoint information to the 'mcedit_waypoints.dat' file in the world directory
     '''
     del self.nbt_waypoints["Waypoints"]
     self.nbt_waypoints["Waypoints"] = nbt.TAG_List()
     for waypoint in self.waypoints.keys():
         if waypoint.split()[0] == "Empty":
             continue
         way = nbt.TAG_Compound()
         way["Name"] = nbt.TAG_String(waypoint.split()[0])
         way["Dimension"] = nbt.TAG_Int(self.waypoints[waypoint][5])
         coords = nbt.TAG_List()
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][0]))
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][1]))
         coords.append(nbt.TAG_Float(self.waypoints[waypoint][2]))
         rot = nbt.TAG_List()
         rot.append(nbt.TAG_Float(self.waypoints[waypoint][3]))
         rot.append(nbt.TAG_Float(self.waypoints[waypoint][4]))
         way["Coordinates"] = coords
         way["Rotation"] = rot
         self.nbt_waypoints["Waypoints"].append(way)
     self.nbt_waypoints.save(
         os.path.join(self.worldDirectory, u"mcedit_waypoints.dat"))
Esempio n. 14
0
    def buildItemTag(self,i):
        # If it's a binary NBT file, just load it
        if i.file != '':
            item_tag = tagsfromfile(i.file)
            # Set the slot and count
            if i.slot != None:
                item_tag['Slot'] = nbt.TAG_Byte(i.slot)
            item_tag['Count'] = nbt.TAG_Byte(i.count)
            return item_tag
        # Otherwise, we will build the compound
        item_tag = nbt.TAG_Compound()
        # Standard stuff
        item_tag['id'] = nbt.TAG_String(i.id)
        item_tag['Damage'] = nbt.TAG_Short(i.damage)
        # Enchantments
        if len(i.enchantments) > 0:
            item_tag['tag'] = nbt.TAG_Compound()
            if (i.flag == 'ENCH_BOOK'):
                item_tag['tag']['StoredEnchantments'] = nbt.TAG_List()
                elist = item_tag['tag']['StoredEnchantments']
            else:
                item_tag['tag']['ench'] = nbt.TAG_List()
                elist = item_tag['tag']['ench']
            for e in i.enchantments:
                e_tag = nbt.TAG_Compound()
                e_tag['id'] = nbt.TAG_Short(e['id'])
                e_tag['lvl'] = nbt.TAG_Short(e['lvl'])
                elist.append(e_tag)
        # Custom Potion Effects
        if i.p_effect != '':
            try:
                item_tag['tag']
            except:
                item_tag['tag'] = nbt.TAG_Compound()

            # Is this a 'basic' potion i.e. no custom effects list
            if (i.p_effect.replace(',','').replace('-','').isdigit()):
                item_tag['tag']['CustomPotionEffects'] = nbt.TAG_List()
                elist = item_tag['tag']['CustomPotionEffects']
                for e in i.p_effect.split(','):
                    id, amp, dur = e.split('-')
                    e_tag = nbt.TAG_Compound()
                    e_tag['Id'] = nbt.TAG_Byte(id)
                    e_tag['Amplifier'] = nbt.TAG_Byte(amp)
                    e_tag['Duration'] = nbt.TAG_Int(dur)
                    # Flags for hiding potion particles
                    if i.flag == 'HIDE_PARTICLES' or i.flag == 'HIDE_ALL':
                        e_tag['ShowParticles'] = nbt.TAG_Byte(0)
                    elist.append(e_tag)
                # If we have a flagparam, use it for the potion's colour
                if i.flagparam != '':
                    item_tag['tag']['CustomPotionColor'] = nbt.TAG_Int(i.flagparam)
            else:
                item_tag['tag']['Potion'] = nbt.TAG_String(i.p_effect)
                # For basic potions there is no need for a custom name
                i.customname = ''
        # Flag for hiding additional text
        if i.flag == 'HIDE_EFFECTS' or i.flag == 'HIDE_ALL':
            try:
                item_tag['tag']
            except:
                item_tag['tag'] = nbt.TAG_Compound()
            item_tag['tag']['HideFlags'] = nbt.TAG_Int(63)    # 63 = Hide everything
        # Naming
        if i.customname != '':
            try:
                item_tag['tag']
            except:
                item_tag['tag'] = nbt.TAG_Compound()
            item_tag['tag']['display'] = nbt.TAG_Compound()
            item_tag['tag']['display']['Name'] = nbt.TAG_String(i.customname)
        # Lore Text
        if i.lore != '' or i.flag == 'FORTUNE':
            try:
                item_tag['tag']
            except:
                item_tag['tag'] = nbt.TAG_Compound()
            try:
                item_tag['tag']['display']
            except:
                item_tag['tag']['display'] = nbt.TAG_Compound()
            item_tag['tag']['display']['Lore'] = nbt.TAG_List()
            if i.flag == 'FORTUNE':
                item_tag['tag']['display'][
                    'Name'] = nbt.TAG_String('Fortune Cookie')
                i.lore = random_line_from_file(cfg.file_fortunes, "...in bed")
                loredata = textwrap.wrap(self.ConvertEscapeChars(i.lore), 30)
                for loretext in loredata[:10]:
                    item_tag['tag']['display']['Lore'].append(
                        nbt.TAG_String(loretext))
            else:
                loredata = i.lore.split(':')
                for loretext in loredata[:10]:
                    item_tag['tag']['display']['Lore'].append(
                        nbt.TAG_String(self.ConvertEscapeChars(loretext[:50])))
        # Flag: Dyed item
        if (i.flag == 'DYED'):
            try:
                item_tag['tag']
            except:
                item_tag['tag'] = nbt.TAG_Compound()
            try:
                item_tag['tag']['display']
            except:
                item_tag['tag']['display'] = nbt.TAG_Compound()
            if i.flagparam == '':
                item_tag['tag']['display']['color'] = nbt.TAG_Int(
                    random.randint(
                        0,
                        16777215))
            else:
                item_tag['tag']['display']['color'] = nbt.TAG_Int(i.flagparam)
        # Flags: Random Book or Painting
        elif (i.flag == 'WRITTEN'):
            item_tag = self.loadrandbooktext()
        elif (i.flag == 'PAINT'):
            item_tag = self.loadrandpainting()
        # Flag: Paint banner or shield with dungeon flag design
        elif (i.flag == 'DUNGEON_FLAG'):
            try:
                item_tag['tag']
            except:
                item_tag['tag'] = nbt.TAG_Compound()
            item_tag['tag']['BlockEntityTag'] = nbt.TAG_Compound()
            item_tag['tag']['BlockEntityTag']['Base'] = nbt.TAG_Int(self.flag['Base'])
            item_tag['tag']['BlockEntityTag']['Patterns'] = nbt.TAG_List()
            for p in self.flag['Patterns']:
                q = nbt.TAG_Compound()
                q['Color'] = nbt.TAG_Int(p[0])
                q['Pattern'] = nbt.TAG_String(p[1])
                item_tag['tag']['BlockEntityTag']['Patterns'].append(q)
            # Set the damage to match the base colour. This is a special case for
            # banner items in chests
            if i.id == 'minecraft:banner':
                item_tag['Damage'] = nbt.TAG_Short(self.flag['Base'])
        # Flag: Give item mob entity tag (spawn eggs)
        elif (i.flag.startswith('ENTITYTAG:')):
            try:
                item_tag['tag']
            except:
                item_tag['tag'] = nbt.TAG_Compound()
            item_tag['tag']['EntityTag'] = nbt.TAG_Compound()
            # ENTITYTAG: is 10 characters, we want everything afterwards
            item_tag['tag']['EntityTag']['id'] = nbt.TAG_String(i.flag[10:])
        # Flag: Give random recipie from recipes.txt
        elif (i.flag == 'RECIPE'):
            try:
                item_tag['tag']
            except:
                item_tag['tag'] = nbt.TAG_Compound()
            item_tag['tag']['Recipes'] = nbt.TAG_List()
            r = random_line_from_file(cfg.file_recipes, "minecraft:crafting_table")
            item_tag['tag']['Recipes'].append(nbt.TAG_String(r))

        # Set the slot and count
        if i.slot != None:
            item_tag['Slot'] = nbt.TAG_Byte(i.slot)
        item_tag['Count'] = nbt.TAG_Byte(i.count)
        return item_tag
Esempio n. 15
0
 def testList():
     tag = nbt.TAG_List()
     tag.append(nbt.TAG_Int(258))
     del tag[0]
Esempio n. 16
0
    def generate_map(self, dungeon, level):
        '''Generate a new map, save it to disk, flush the cache, and return a
        map item NBT with the appropriate map ID.'''

        dungeon_key = '%s,%s' % (dungeon.position.x, dungeon.position.z)
        if dungeon_key not in self.mapcache['used']:
            self.mapcache['used'][dungeon_key] = set([])

        # Find a map id. Look in the available list for old mcdungeon maps
        # that can be reused. If not, bump up the idcount and use that.
        if len(self.mapcache['available']) == 0:
            # Initialize the map count if it doesn't exist.
            if 'map' not in self.idcounts:
                self.idcounts['map'] = nbt.TAG_Short(-1)

            self.idcounts['map'].value += 1
            mapid = self.idcounts['map'].value
            self.mapcache['used'][dungeon_key].add(mapid)
        else:
            mapid = self.mapcache['available'].pop()
            self.mapcache['used'][dungeon_key].add(mapid)
        filename = os.path.join(self.mapstore, 'map_%d.dat' % (mapid))

        # Setup the defaults.
        # Offset will be way off somewhere were players are unlikely to go
        # to avoid the maps from being overwritten. Nothing else really
        # matters.
        tags = nbt.TAG_Compound()
        tags['data'] = nbt.TAG_Compound()
        tags['data']['scale'] = nbt.TAG_Byte(0)
        tags['data']['xCenter'] = nbt.TAG_Int(-12500000)
        tags['data']['zCenter'] = nbt.TAG_Int(-12500000)
        tags['data']['height'] = nbt.TAG_Short(128)
        tags['data']['width'] = nbt.TAG_Short(128)
        tags['data']['dimension'] = nbt.TAG_Byte(0)
        tags['data']['colors'] = nbt.TAG_Byte_Array(zeros(16384, uint8))

        # Generate the map.
        blocks = dungeon.blocks
        colors = tags['data']['colors'].value
        y = level * dungeon.room_height - 3
        # Scale the map. We only scale up, not down since scaling
        # looks terrible.
        max_dungeon = max(dungeon.xsize * dungeon.room_size,
                          dungeon.zsize * dungeon.room_size)
        max_dungeon = max(128, max_dungeon)

        # If the size is less than 8, try to center it.
        xoffset = 0
        zoffset = 0
        if dungeon.xsize * dungeon.room_size < 128:
            xoffset = (128 - dungeon.xsize * dungeon.room_size) / 2
        if dungeon.zsize * dungeon.room_size < 128:
            zoffset = (128 - dungeon.zsize * dungeon.room_size) / 2

        # Draw pixels on the map corresponding to blocks just above
        # floor level. Color chests and spawners. Hide things that should be
        # hidden.
        for x in xrange(128):
            for z in xrange(128):
                block = Vec(x * max_dungeon / 128 - xoffset, y,
                            z * max_dungeon / 128 - zoffset)
                if block in blocks:
                    mat = blocks[block].material
                    if mat == materials.StonePressurePlate:
                        colors[x + z * 128] = 10
                    elif blocks[block].hide is True:
                        colors[x + z * 128] = 0
                    elif blocks[block].blank is True:
                        colors[x + z * 128] = 0
                    elif mat == materials.Air:
                        colors[x + z * 128] = 10
                    elif mat == materials.Spawner:
                        colors[x + z * 128] = 48
                    elif (mat == materials.Chest
                          or mat == materials.TrappedChest):
                        colors[x + z * 128] = 42
                    else:
                        colors[x + z * 128] = 54
                else:
                    colors[x + z * 128] = 0

        # Draw the level number in the corner
        digits = [[0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0],
                  [0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1],
                  [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1],
                  [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0],
                  [1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1],
                  [1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1],
                  [0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1],
                  [1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0],
                  [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
                  [1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1]]
        sx = 120
        if level < 10:
            sx = 124
        sz = 123
        for d in str(level):
            for x in xrange(3):
                for z in xrange(5):
                    if digits[int(d)][x + z * 3] == 1:
                        colors[x + sx + (z + sz) * 128] = 16
            sx += 4

        # Save the map file, cache, and idcount.dat
        tags.save(filename)
        self.update_mapstore()

        # Return a map item
        item = nbt.TAG_Compound()
        item['id'] = nbt.TAG_String(items.byName('map').id)
        item['Damage'] = nbt.TAG_Short(mapid)
        item['Count'] = nbt.TAG_Byte(1)
        item['tag'] = nbt.TAG_Compound()
        item['tag']['display'] = nbt.TAG_Compound()
        name = dungeon.dungeon_name + ' Lv {l}'
        item['tag']['display']['Name'] = nbt.TAG_String(name.format(l=level))
        item['tag']['display']['MapColor'] = nbt.TAG_Int(self.mapcolor)
        print item['tag']['display']['Name'].value

        return item
Esempio n. 17
0
    def testCreate():
        "Create an indev level."

        # The root of an NBT file is always a TAG_Compound.
        level = nbt.TAG_Compound(name="MinecraftLevel")

        # Subtags of a TAG_Compound are automatically named when you use the [] operator.
        level["About"] = nbt.TAG_Compound()
        level["About"]["Author"] = nbt.TAG_String("codewarrior")
        level["About"]["CreatedOn"] = nbt.TAG_Long(time.time())

        level["Environment"] = nbt.TAG_Compound()
        level["Environment"]["SkyBrightness"] = nbt.TAG_Byte(16)
        level["Environment"]["SurroundingWaterHeight"] = nbt.TAG_Short(32)
        level["Environment"]["FogColor"] = nbt.TAG_Int(0xcccccc)

        entity = nbt.TAG_Compound()
        entity["id"] = nbt.TAG_String("Creeper")
        entity["Pos"] = nbt.TAG_List([nbt.TAG_Float(d) for d in (32.5, 64.0, 33.3)])

        level["Entities"] = nbt.TAG_List([entity])

        # You can also create and name a tag before adding it to the compound.
        spawn = nbt.TAG_List((nbt.TAG_Short(100), nbt.TAG_Short(45), nbt.TAG_Short(55)))
        spawn.name = "Spawn"

        mapTag = nbt.TAG_Compound()
        mapTag.add(spawn)
        mapTag.name = "Map"
        level.add(mapTag)

        mapTag2 = nbt.TAG_Compound([spawn])
        mapTag2.name = "Map"

        # I think it looks more familiar with [] syntax.

        l, w, h = 128, 128, 128
        mapTag["Height"] = nbt.TAG_Short(h)  # y dimension
        mapTag["Length"] = nbt.TAG_Short(l)  # z dimension
        mapTag["Width"] = nbt.TAG_Short(w)  # x dimension

        # Byte arrays are stored as numpy.uint8 arrays.

        mapTag["Blocks"] = nbt.TAG_Byte_Array()
        mapTag["Blocks"].value = numpy.zeros(l * w * h, dtype=numpy.uint8)  # create lots of air!

        # The blocks array is indexed (y,z,x) for indev levels, so reshape the blocks
        mapTag["Blocks"].value.shape = (h, l, w)

        # Replace the bottom layer of the indev level with wood
        mapTag["Blocks"].value[0, :, :] = 5

        # This is a great way to learn the power of numpy array slicing and indexing.

        mapTag["Data"] = nbt.TAG_Byte_Array()
        mapTag["Data"].value = numpy.zeros(l * w * h, dtype=numpy.uint8)

        # Save a few more tag types for completeness

        level["ShortArray"] = nbt.TAG_Short_Array(numpy.zeros((16, 16), dtype='uint16'))
        level["IntArray"] = nbt.TAG_Int_Array(numpy.zeros((16, 16), dtype='uint32'))
        level["Float"] = nbt.TAG_Float(0.3)

        return level
Esempio n. 18
0
def buildWorld(x, z):

    global world
    global peak
    global y_min
    global map_type
    global myfile
    global x_extent
    global material
    global elevation

    if z == 1:
        with open(tf, "a") as myfile:
            myfile.write("x = %r out of %r\n" % (x, x_extent))
            myfile.close()

    y = elevation[x][z]
    my_id = material[x][z]

    block_id, block_data, depth = block_id_lookup[my_id]
    actual_y = y + y_min
    if actual_y > peak[1] or (peak[1] == 255 and y != 0):
        peak = [x + 1, actual_y + 15, z]

    # Don't fill up the whole map from bedrock, just draw a shell.
    # this means there is a big cavern under everything... i think
    start_at = max(1, actual_y - depth - y_min)

    # If we were going to optimize this code, this is where the
    # optimization would go. Lay down the stone in big slabs and
    # then sprinkle goodies into it.
    stop_at = actual_y - depth
    for elev in range(start_at, stop_at):
        #    if map_type == 'map' or elev == stop_at - 1:
        #        block = m.Stone.ID
        #    else:
        #        block = 7
        world.setBlockAt(x, elev, z, 7)

    # now place the materials
    start_at = actual_y - depth
    stop_at = actual_y + 1

    #        if random.random() < 0.25:
    #            Chicken = Entity.Create('Chicken')
    #            Entity.setpos(Chicken, (x, actual_y + 3, z))
    #            world.addEntity(Chicken)

    # Add in if statements as you like for various special cases for placing materials
    if block_id == m.Water.ID:
        # Carve a little channel for active water so it doesn't overflow.
        start_at -= 1
        #            stop_at -= 1
        choice = random.random()
        if choice < 0.04:
            world.setBlockAt(
                x, elev + 2, z,
                111)  # Lily pad, not sure what elev works for this
            world.setBlockDataAt(x, elev + 2, z, 0)
            #  Squid = Entity.Create('Squid')
            #  Entity.setpos(Squid, (x, actual_y - 1, z))
            #  world.addEntity(Squid)

    for elev in range(start_at, stop_at):
        world.setBlockAt(x, elev, z, block_id)
        if block_data:
            world.setBlockDataAt(x, elev, z, block_data)
        # world.setBlockAt(x, elev+1, z , 63) # sign block
        # world.setBlockDataAt(x, elev+1, z, 0)
        # Sign = TileEntity.Create("Sign")
        # TileEntity.setpos(Sign, (x, elev+1, z))
        # Sign['Text1'] = nbt.TAG_String('TA_test_1')
        # world.addTileEntity(Sign)

    if my_id == 10:  # Upland fens and swamp
        world.setBlockAt(x, elev + 1, z, 31)
        world.setBlockDataAt(x, elev + 1, z, 2)

    elif my_id == 11:  # Marsh fens and swamp
        world.setBlockAt(x, elev + 1, z, 31)
        world.setBlockDataAt(x, elev + 1, z, 1)


#  elif my_id == 8: # non-woodland rivers
#      choice = random.random()
#      if choice < 0.05:
#        world.setBlockAt(x, elev+1, z , 111) # Lily pad, not sure what elev works for this
#        world.setBlockDataAt(x, elev+1, z, 0)

    elif my_id == 14:  # Acid grassland / Heather grassland
        choice = random.random()
        if choice < 0.5:
            if choice < 0.25:
                world.setBlockAt(x, elev + 1, z, 38)
                world.setBlockDataAt(x, elev + 1, z, 7)
            else:
                world.setBlockAt(x, elev + 1, z, 38)
                world.setBlockDataAt(x, elev + 1, z, 2)
        else:
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 15:  # Calcareous grassland
        choice = random.random()
        if choice < 0.02:
            Rabbit = Entity.Create('Rabbit')
            Entity.setpos(Rabbit, (x, actual_y + 3, z))
            Rabbit['Variant'] = nbt.TAG_Int(random.choice([0]))
            world.addEntity(Rabbit)

        if 0.02 <= choice <= 0.2:  # add red flowers
            world.setBlockAt(x, elev + 1, z, 38)
            world.setBlockDataAt(x, elev + 1, z, 7)

        if 0.2001 <= choice <= 0.6:  # add white flowers
            world.setBlockAt(x, elev + 1, z, 38)
            world.setBlockDataAt(x, elev + 1, z, 4)

        if choice > 0.6:  # add grass
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 16:  # Non-woodland grassland
        world.setBlockAt(x, elev + 1, z, 31)
        world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 17:  # Upland heather
        choice = random.random()
        if choice < 0.5:
            if choice < 0.25:
                world.setBlockAt(x, elev + 1, z, 38)
                world.setBlockDataAt(x, elev + 1, z, 7)
            else:
                world.setBlockAt(x, elev + 1, z, 38)
                world.setBlockDataAt(x, elev + 1, z, 2)

    elif my_id == 18:  # Heather/moorland
        choice = random.random()
        if choice < 0.5:
            world.setBlockAt(x, elev + 1, z, 38)
            world.setBlockDataAt(x, elev + 1, z, 2)
        else:
            world.setBlockAt(x, elev + 1, z, 32)
            world.setBlockDataAt(x, elev + 1, z, 0)

    elif my_id == 19:  # Broadleaf decidious woodland
        choice = random.random()
        if choice < 0.05:
            world = buildTree('broad', world, elev, z, x)

        if 0.05 <= choice <= 0.09:
            world.setBlockAt(x, elev + 1, z, 40)
            world.setBlockDataAt(x, elev + 1, z, 0)

        if choice > 0.09:
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 20:  # Coniferous woodland
        choice = random.random()
        if choice < 0.05:
            world = buildTree('conf', world, elev, z, x)

        if 0.05 <= choice <= 0.09:
            world.setBlockAt(x, elev + 1, z, 39)
            world.setBlockDataAt(x, elev + 1, z, 0)

        if choice > 0.09:
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 21:  # mixed woodland
        choice = random.random()
        if choice < 0.05:
            world = buildTree('mixed', world, elev, z, x)

        # add mushrooms
        if 0.05 <= choice <= 0.09:
            world.setBlockAt(x, elev + 1, z, 40)
            world.setBlockDataAt(x, elev + 1, z, 0)

        # add grass
        if choice > 0.09:
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 22:  # low density woodland
        choice = random.random()
        if choice < 0.025:
            world = buildTree('mixed', world, elev, z, x)

        # add mushrooms
        if 0.05 <= choice <= 0.09:
            world.setBlockAt(x, elev + 1, z, 39)
            world.setBlockDataAt(x, elev + 1, z, 0)

        # add grass
        if choice > 0.09:
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 24:  # non woodland-Agricultural land
        world.setBlockAt(x, elev + 1, z, 38)  # white flowers - azure bluet
        world.setBlockDataAt(x, elev + 1, z, 3)

    elif my_id == 29:  # Beetroot
        world.setBlockAt(x, elev + 1, z, 141)
        world.setBlockDataAt(x, elev + 1, z, 7)

    elif my_id == 30:  # field bean
        world.setBlockAt(x, elev + 1, z, 104)
        world.setBlockDataAt(x, elev + 1, z, 7)

    elif my_id == 31:  # maize
        world.setBlockAt(x, elev + 1, z, m.Crops.ID)
        world.setBlockDataAt(x, elev + 1, z, 6)

    elif my_id == 32:  # oilseed rape
        world.setBlockAt(x, elev + 1, z, 37)
        world.setBlockDataAt(x, elev + 1, z, 0)

    elif my_id == 33:  # farmland other
        world.setBlockAt(x, elev + 1, z, 38)
        world.setBlockDataAt(x, elev + 1, z, 8)

    elif my_id == 34:  # potatoes
        world.setBlockAt(x, elev + 1, z, 142)
        world.setBlockDataAt(x, elev + 1, z, 7)

    elif my_id == 35:  # Farm - spring barley
        world.setBlockAt(x, elev + 1, z, m.Crops.ID)
        world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 36:  # Farm - spring wheat
        world.setBlockAt(x, elev + 1, z, m.Crops.ID)
        world.setBlockDataAt(x, elev + 1, z, 5)

    elif my_id == 37:  # Farm - winter barley
        world.setBlockAt(x, elev + 1, z, m.Crops.ID)
        world.setBlockDataAt(x, elev + 1, z, 3)

    elif my_id == 38:  # Farm - winter wheat
        world.setBlockAt(x, elev + 1, z, m.Crops.ID)
        world.setBlockDataAt(x, elev + 1, z, 6)

    elif my_id == 102:  # bridge
        world.setBlockAt(x, elev + 2, z, 44)
        world.setBlockDataAt(x, elev + 2, z, 6)

    elif my_id == 25:  # Urban

        # set height width and depth randomly
        pH = random.random()
        if pH < 0.2:
            H = 12
        elif pH < 0.6:
            H = 10
        else:
            H = 8

        pW = random.random()
        if pW < 0.2:
            W = 4
        elif pW < 0.6:
            W = 3
        else:
            W = 2

        pD = random.random()
        if pD < 0.2:
            D = 4
        elif pD < 0.6:
            D = 3
        else:
            D = 2

        if numpy.all(material[x - W:x + W,
                              z - D:z + D] == 25):  # Block of urban

            #MatPres = [] # empty array to get materials present

            empty = 0

            for nY in range(actual_y + 1, actual_y + H +
                            2):  # Loop through and see what is there
                for nX in range(x - W - 1, x + W +
                                1):  # extend x and y to allow 'streets'
                    for nZ in range(z - D - 1, z + D + 1):
                        if world.blockAt(nX, nY, nZ) != 0:
                            empty = 1
                            break
                    if empty == 1:
                        break
                if empty == 1:
                    break

            # if all(item == 0 for item in MatPres): # If we have space to build the house
            if empty == 0:

                wallMat = random.choice([(125, 2), (98, 0), (45, 0)])

                for nY in range(actual_y - 1, actual_y + H +
                                1):  # Loop through and build the house

                    # set block type for level
                    if nY == max(range(actual_y + 1,
                                       actual_y + H + 1)):  # Roof
                        blockType = random.choice([(44, 0), (44, 1), (44, 5)])
                    elif nY - actual_y == 2 or nY - actual_y == 4 or nY - actual_y == 6 or nY - actual_y == 8 or nY - actual_y == 10:  # Windows level
                        blockType = (m.Glass.ID, 0)
                    else:  # Wall
                        blockType = wallMat

                    for nX in range(x - W, x + W):

                        # make pillars and place block
                        for nZ in range(z - D, z + D):

                            bT = blockType  # save to reset

                            # Make pillars
                            xEdge = nX == min(range(
                                x - W, x + W)) or nX == max(range(
                                    x - W, x + W))
                            zEdge = nZ == min(range(
                                z - D, z + D)) or nZ == max(range(
                                    z - D, z + D))
                            if xEdge and zEdge:
                                if nY != max(
                                        range(actual_y + 1, actual_y + H + 1)):
                                    blockType = wallMat

                            if nY - actual_y < 1:
                                blockType = (1, 6)

                            world.setBlockAt(nX, nY, nZ, blockType[0])
                            world.setBlockDataAt(nX, nY, nZ, blockType[1])

                            blockType = bT

            else:  # urban but we can't put a house
                if random.random() < 0.02:  # Add a cat
                    Cat = Entity.Create('Ocelot')
                    Entity.setpos(Cat, (x, actual_y + 2, z))  # Where to put it
                    Cat['CatType'] = nbt.TAG_Int(random.choice(
                        [1, 2, 3]))  # What kind of cat
                    world.addEntity(Cat)  # Add it
                if random.random() < 0.05:  # Add a person
                    Villager = Entity.Create('Villager')
                    Entity.setpos(Villager,
                                  (x, actual_y + 2, z))  # Where to put it
                    Villager['Profession'] = nbt.TAG_Int(
                        random.choice([0, 1, 2, 3, 4, 5]))  # What kind of cat
                    world.addEntity(Villager)  # Add it

    elif my_id == 251:  # Suburban

        # set height width and depth randomly
        pH = random.random()
        if pH < 0.2:
            H = 3
        elif pH < 0.6:
            H = 4
        else:
            H = 4

        pW = random.random()
        if pW < 0.2:
            W = 4
        elif pW < 0.6:
            W = 3
        else:
            W = 2

        pD = random.random()
        if pD < 0.2:
            D = 4
        elif pD < 0.6:
            D = 3
        else:
            D = 2

        if numpy.all(material[x - W:x + W,
                              z - D:z + D] == 251):  # Block of urban

            #MatPres = [] # empty array to get materials present

            empty = 0

            for nY in range(actual_y + 1, actual_y + H +
                            2):  # Loop through and see what is there
                for nX in range(x - W - 2, x + W +
                                2):  # extend x and y to allow 'streets'
                    for nZ in range(z - D - 1, z + D + 1):
                        if world.blockAt(nX, nY, nZ) != 0:
                            empty = 1
                            break
                    if empty == 1:
                        break
                if empty == 1:
                    break

            # if all(item == 0 for item in MatPres): # If we have space to build the house
            if empty == 0:

                wallMat = random.choice([(43, 2), (5, 0), (5, 2)])

                for nY in range(actual_y - 1, actual_y + H +
                                1):  # Loop through and build the house

                    # set block type for level
                    if nY == max(range(actual_y + 1,
                                       actual_y + H + 1)):  # Roof
                        blockType = random.choice([(126, 1), (126, 5),
                                                   (126, 4)])
                    elif nY - actual_y == 2 or nY - actual_y == 4 or nY - actual_y == 6:  # Windows level
                        blockType = (m.Glass.ID, 0)
                    else:  # Wall
                        blockType = wallMat

                    for nX in range(x - W, x + W):

                        # make pillars and place block
                        for nZ in range(z - D, z + D):

                            bT = blockType  # save to reset

                            # Make pillars
                            xEdge = nX == min(range(
                                x - W, x + W)) or nX == max(range(
                                    x - W, x + W))
                            zEdge = nZ == min(range(
                                z - D, z + D)) or nZ == max(range(
                                    z - D, z + D))
                            if xEdge and zEdge:
                                if nY != max(
                                        range(actual_y + 1, actual_y + H + 1)):
                                    blockType = wallMat

                            if nY - actual_y < 1:
                                blockType = (1, 6)

                            world.setBlockAt(nX, nY, nZ, blockType[0])
                            world.setBlockDataAt(nX, nY, nZ, blockType[1])

                            blockType = bT
            else:  # urban but we can't put a house
                if random.random() < 0.02:  # Add a cat
                    Cat = Entity.Create('Ocelot')
                    Entity.setpos(Cat, (x, actual_y + 2, z))  # Where to put it
                    Cat['CatType'] = nbt.TAG_Int(random.choice(
                        [1, 2, 3]))  # What kind of cat
                    world.addEntity(Cat)  # Add it
                if random.random() < 0.075:  # Add a person
                    Villager = Entity.Create('Villager')
                    Entity.setpos(Villager,
                                  (x, actual_y + 2, z))  # Where to put it
                    Villager['Profession'] = nbt.TAG_Int(
                        random.choice([0, 1, 2, 3, 4, 5]))  # What kind of cat
                    world.addEntity(Villager)  # Add it

    elif my_id == 12:  # Grassland (semi-natural)
        choice = random.random()
        if choice < 0.5:
            if choice < 0.25:
                world.setBlockAt(x, elev + 1, z, 38)
                world.setBlockDataAt(x, elev + 1, z, 0)
            else:
                world.setBlockAt(x, elev + 1, z, 37)
                world.setBlockDataAt(x, elev + 1, z, 0)
        else:
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 131:  # neutral grassland
        choice = random.random()
        if choice < 0.2:
            if choice < 0.1:
                world.setBlockAt(x, elev + 1, z, 38)
                world.setBlockDataAt(x, elev + 1, z, 4)
            else:
                world.setBlockAt(x, elev + 1, z, 38)
                world.setBlockDataAt(x, elev + 1, z, 3)

        if random.random() < 0.005:  # add Sheep
            Sheep = Entity.Create('Sheep')
            Entity.setpos(Sheep, (x, actual_y + 3, z))
            Sheep['Variant'] = nbt.TAG_Int(random.choice([0]))
            world.addEntity(Sheep)

    elif my_id == 13:  # improved grassland #1
        if random.random() < 0.005:  # add Sheep
            Sheep = Entity.Create('Sheep')
            Entity.setpos(Sheep, (x, actual_y + 3, z))
            Sheep['Variant'] = nbt.TAG_Int(random.choice([0]))
            world.addEntity(Sheep)

    elif my_id == 313:  # Good quality semi-improved grassland
        choice = random.random()
        if choice < 0.02:
            if choice < 0.005:  # add horse
                Horse = Entity.Create('Horse')
                Entity.setpos(Horse, (x, actual_y + 3, z))
                Horse['Variant'] = nbt.TAG_Int(random.choice([0]))
                world.addEntity(Horse)
            else:
                # add rabbit
                Rabbit = Entity.Create('Rabbit')
                Entity.setpos(Rabbit, (x, actual_y + 3, z))
                Rabbit['Variant'] = nbt.TAG_Int(random.choice([0]))
                world.addEntity(Rabbit)

    elif my_id == 314:  # Upland Hay Meadow
        choice = random.random()
        if choice < 0.03:
            Rabbit = Entity.Create('Rabbit')
            Entity.setpos(Rabbit, (x, actual_y + 3, z))
            Rabbit['Variant'] = nbt.TAG_Int(random.choice([0]))
            world.addEntity(Rabbit)

        if 0.03 <= choice <= 0.1:  # add red flowers
            world.setBlockAt(x, elev + 1, z, 38)
            world.setBlockDataAt(x, elev + 1, z, 0)

        if 0.1001 <= choice <= 0.4:  # add white flowers
            world.setBlockAt(x, elev + 1, z, 38)
            world.setBlockDataAt(x, elev + 1, z, 6)

        if choice > 0.4:  # add grass
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    elif my_id == 132:  # improved grassland #2
        if random.random() < 0.01:  # add Cow
            Cow = Entity.Create('Cow')
            Entity.setpos(Cow, (x, actual_y + 3, z))
            Cow['Variant'] = nbt.TAG_Int(random.choice([0]))
            world.addEntity(Cow)

    elif my_id == 133:  # lowland meadows
        choice = random.random()
        if choice < 0.02:
            Rabbit = Entity.Create('Rabbit')
            Entity.setpos(Rabbit, (x, actual_y + 3, z))
            Rabbit['Variant'] = nbt.TAG_Int(random.choice([0]))
            world.addEntity(Rabbit)

        if 0.02 <= choice <= 0.2:  # add red flowers
            world.setBlockAt(x, elev + 1, z, 38)
            world.setBlockDataAt(x, elev + 1, z, 0)

        if 0.2001 <= choice <= 0.7:  # add white flowers
            world.setBlockAt(x, elev + 1, z, 38)
            world.setBlockDataAt(x, elev + 1, z, 6)

        if choice > 0.7:  # add grass
            world.setBlockAt(x, elev + 1, z, 31)
            world.setBlockDataAt(x, elev + 1, z, 1)

    # add snow
    elif my_id == 78:
        world.setBlockAt(x, elev + 1, z, m.SnowLayer.ID)

    # add glass walls between walls
    elif my_id == 888:  # glass wall
        for nY in range(0, 200):  # Loop through and build the house
            world.setBlockAt(x, nY, z, 20)
            world.setBlockDataAt(x, nY, z, 0)
Esempio n. 19
0
 def buildItemTag(self, i):
     # If it's a binary NBT file, just load it
     if i.file != '':
         item_tag = nbt.load(i.file)
         # Set the slot and count
         if i.slot != None:
             item_tag['Slot'] = nbt.TAG_Byte(i.slot)
         item_tag['Count'] = nbt.TAG_Byte(i.count)
         return item_tag
     # Otherwise, we will build the compound
     item_tag = nbt.TAG_Compound()
     # Standard stuff
     item_tag['id'] = nbt.TAG_Short(i.id)
     item_tag['Damage'] = nbt.TAG_Short(i.damage)
     # Enchantments
     if len(i.enchantments) > 0:
         item_tag['tag'] = nbt.TAG_Compound()
         if (i.flag == 'ENCH_BOOK'):
             item_tag['tag']['StoredEnchantments'] = nbt.TAG_List()
             elist = item_tag['tag']['StoredEnchantments']
         else:
             item_tag['tag']['ench'] = nbt.TAG_List()
             elist = item_tag['tag']['ench']
         for e in i.enchantments:
             e_tag = nbt.TAG_Compound()
             e_tag['id'] = nbt.TAG_Short(e['id'])
             e_tag['lvl'] = nbt.TAG_Short(e['lvl'])
             elist.append(e_tag)
     # Custom Potion Effects
     if i.p_effect != '':
         try:
             item_tag['tag']
         except:
             item_tag['tag'] = nbt.TAG_Compound()
         item_tag['tag']['CustomPotionEffects'] = nbt.TAG_List()
         elist = item_tag['tag']['CustomPotionEffects']
         for e in i.p_effect.split(','):
             id, amp, dur = e.split('-')
             e_tag = nbt.TAG_Compound()
             e_tag['Id'] = nbt.TAG_Byte(id)
             e_tag['Amplifier'] = nbt.TAG_Byte(amp)
             e_tag['Duration'] = nbt.TAG_Int(dur)
             # Flags for hiding potion particles
             if i.flag == 'HIDE_PARTICLES' or i.flag == 'HIDE_ALL':
                 e_tag['ShowParticles'] = nbt.TAG_Byte(0)
             elist.append(e_tag)
     # Flag for hiding additional text
     if i.flag == 'HIDE_EFFECTS' or i.flag == 'HIDE_ALL':
         try:
             item_tag['tag']
         except:
             item_tag['tag'] = nbt.TAG_Compound()
         item_tag['tag']['HideFlags'] = nbt.TAG_Int(
             63)  # 63 = Hide everything
     # Naming
     if i.customname != '':
         try:
             item_tag['tag']
         except:
             item_tag['tag'] = nbt.TAG_Compound()
         item_tag['tag']['display'] = nbt.TAG_Compound()
         item_tag['tag']['display']['Name'] = nbt.TAG_String(i.customname)
     # Lore Text
     if i.lore != '' or i.flag == 'FORTUNE':
         try:
             item_tag['tag']
         except:
             item_tag['tag'] = nbt.TAG_Compound()
         try:
             item_tag['tag']['display']
         except:
             item_tag['tag']['display'] = nbt.TAG_Compound()
         item_tag['tag']['display']['Lore'] = nbt.TAG_List()
         if i.flag == 'FORTUNE':
             item_tag['tag']['display']['Name'] = nbt.TAG_String(
                 'Fortune Cookie')
             i.lore = self.loadrandfortune()
             loredata = textwrap.wrap(self.ConvertEscapeChars(i.lore), 30)
             for loretext in loredata[:10]:
                 item_tag['tag']['display']['Lore'].append(
                     nbt.TAG_String(loretext))
         else:
             loredata = i.lore.split(':')
             for loretext in loredata[:10]:
                 item_tag['tag']['display']['Lore'].append(
                     nbt.TAG_String(self.ConvertEscapeChars(loretext[:50])))
     # Dyed
     if (i.flag == 'DYED'):
         try:
             item_tag['tag']
         except:
             item_tag['tag'] = nbt.TAG_Compound()
         try:
             item_tag['tag']['display']
         except:
             item_tag['tag']['display'] = nbt.TAG_Compound()
         if i.flagparam == '':
             item_tag['tag']['display']['color'] = nbt.TAG_Int(
                 random.randint(0, 16777215))
         else:
             item_tag['tag']['display']['color'] = nbt.TAG_Int(i.flagparam)
     # special cases for written books and paintings
     if (i.flag == 'WRITTEN'):
         item_tag = self.loadrandbooktext()
     if (i.flag == 'PAINT'):
         item_tag = self.loadrandpainting()
     # Set the slot and count
     if i.slot != None:
         item_tag['Slot'] = nbt.TAG_Byte(i.slot)
     item_tag['Count'] = nbt.TAG_Byte(i.count)
     return item_tag