├── test2.py ├── pycraft_minetest ├── __init__.py ├── security.py ├── settings.py ├── minecraft-pi-edition-LICENSE.txt ├── event.py ├── entity.py ├── mcpi_protocol_spec.txt ├── vec3.py ├── util.py ├── connection.py ├── blocklist.py ├── minecraft.py ├── nbt.py └── main.py ├── setup.cfg ├── recipes ├── new.py ├── hello_minetest.py ├── maze.py ├── traps.py ├── stuffed_sphere.py ├── sphere_galaxy.py ├── gold_detector.py ├── magic_cube.py ├── turtle_square_spiral.py ├── mutant_sphere.py ├── turtle_pyramid.py ├── turtle_circles.py ├── turtle_flowers.py ├── clock.py └── maze1.csv ├── MANIFEST ├── setup.py ├── README.md ├── .gitignore ├── test.py └── LICENSE /test2.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | -------------------------------------------------------------------------------- /pycraft_minetest/__init__.py: -------------------------------------------------------------------------------- 1 | from . main import * 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /recipes/new.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | chat("Hello Minetest!") 4 | -------------------------------------------------------------------------------- /recipes/hello_minetest.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | chat("Hello Minetest!") 4 | -------------------------------------------------------------------------------- /pycraft_minetest/security.py: -------------------------------------------------------------------------------- 1 | AUTHENTICATION_USERNAME=None 2 | AUTHENTICATION_PASSWORD=None 3 | -------------------------------------------------------------------------------- /recipes/maze.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | 4 | # Call the "maze" function passing the path to 5 | # the CSV file containing the maze schema 6 | maze("maze1.csv") 7 | -------------------------------------------------------------------------------- /recipes/traps.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | # FOREVER 4 | while True: 5 | # If you're stepping on a block of diamond... 6 | if over(diamond): 7 | # Then create a lava sphere around you! 8 | sphere(lava, 2) 9 | -------------------------------------------------------------------------------- /recipes/stuffed_sphere.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | # Create a sphere of glass (so you can see through) 4 | sphere(glass, 20, z=25) 5 | # Now create a sphere of lava (but also water or sand could work) 6 | # that will be generated inside the glass sphere 7 | sphere(lava, 19, z=25) 8 | -------------------------------------------------------------------------------- /recipes/sphere_galaxy.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | for i in range(random.randint(50, 100)): 4 | sphere([wool, random.randint(0, 12)], 5 | random.randint(1, 30), 6 | x=random.randint(-200, 200), 7 | y=random.randint(-200, 200), 8 | z=random.randint(-200, 200)) 9 | -------------------------------------------------------------------------------- /pycraft_minetest/settings.py: -------------------------------------------------------------------------------- 1 | from os import environ 2 | 3 | MINECRAFT_POCKET_EDITION = 0 4 | MINECRAFT_PI = 1 5 | MINECRAFT_DESKTOP = 2 6 | 7 | minecraftType = MINECRAFT_DESKTOP 8 | 9 | try: 10 | minecraftType = int(environ['MINECRAFT_TYPE']) 11 | except: 12 | pass 13 | 14 | isPE = ( minecraftType != MINECRAFT_DESKTOP ) 15 | 16 | -------------------------------------------------------------------------------- /recipes/gold_detector.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | import time 3 | 4 | # Forever 5 | while True: 6 | # If there is at least one block of gold 7 | # in a range of (default) 10 units around me... 8 | if near(gold): 9 | # Write it on the game chat 10 | chat("There is gold nearby!") 11 | # Delay 12 | time.sleep(1) 13 | -------------------------------------------------------------------------------- /pycraft_minetest/minecraft-pi-edition-LICENSE.txt: -------------------------------------------------------------------------------- 1 | *** The real license isn't finished yet, here's what goes in plain english *** 2 | 3 | You may execute the minecraft-pi binary on a Raspberry Pi or an emulator 4 | You may use any of the source code included in the distribution for any purpose (except evil) 5 | 6 | You may not redistribute any modified binary parts of the distribution 7 | -------------------------------------------------------------------------------- /recipes/magic_cube.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | import time 3 | 4 | (conn, player) = connect_server() 5 | 6 | while True: 7 | 8 | # For each number in a range 9 | for color in range(12): 10 | # Create a cube of wool blocks 11 | # with that number as block-subtype 12 | cube([wool, color], 4, x=-2, y=-5, z=-2) 13 | 14 | # Delay 15 | time.sleep(0.1) 16 | -------------------------------------------------------------------------------- /recipes/turtle_square_spiral.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | # Instance a Turtle object 4 | uga = Turtle(obsidian) 5 | 6 | # Create a variable for the side of the spiral 7 | side = 1 8 | 9 | while True: 10 | # Move the Turtle forward of "side" steps 11 | uga.forward(side) 12 | # Make the Turtle turn right of 90 (try to change it) degrees 13 | uga.down(90) 14 | # Increment the side variable 15 | side = side + 1 16 | -------------------------------------------------------------------------------- /MANIFEST: -------------------------------------------------------------------------------- 1 | # file GENERATED by distutils, do NOT edit 2 | setup.cfg 3 | setup.py 4 | pycraft_minetest/__init__.py 5 | pycraft_minetest/blocklist.py 6 | pycraft_minetest/connection.py 7 | pycraft_minetest/entity.py 8 | pycraft_minetest/event.py 9 | pycraft_minetest/main.py 10 | pycraft_minetest/minecraft.py 11 | pycraft_minetest/nbt.py 12 | pycraft_minetest/security.py 13 | pycraft_minetest/settings.py 14 | pycraft_minetest/util.py 15 | pycraft_minetest/vec3.py 16 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | setup( 3 | name='pycraft_minetest', 4 | packages=['pycraft_minetest'], 5 | version='0.8', 6 | description='Modified, simplified and improved libraries to code in Python via Minetest.', 7 | author='alenorfo & gmenegoz', 8 | author_email='ale.norfo@gmail.com', 9 | url='https://github.com/sprintingkiwi/pycraft_lib', 10 | download_url='https://github.com/sprintingkiwi/pycraft_lib/tarball/0.6', 11 | keywords=['game', 'development', 'learning', 'education', 'turtle'], 12 | classifiers=[], 13 | ) 14 | -------------------------------------------------------------------------------- /recipes/mutant_sphere.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | # Store player position in a variable 4 | pos = where() 5 | # Write on chat that position (just as a test) 6 | chat(pos) 7 | 8 | # Forever 9 | while True: 10 | 11 | # Sequentially create many spheres with different materials 12 | # but in the same absolute position 13 | sphere(grass, 10, x=pos.x+25, y=pos.y, z=pos.z, absolute=True) 14 | time.sleep(1) 15 | 16 | sphere(gold, 10, x=pos.x+25, y=pos.y, z=pos.z, absolute=True) 17 | time.sleep(1) 18 | 19 | sphere(ice, 10, x=pos.x+25, y=pos.y, z=pos.z, absolute=True) 20 | time.sleep(1) 21 | -------------------------------------------------------------------------------- /recipes/turtle_pyramid.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | # Create a Turtle object 4 | pyr = Turtle(iron) 5 | 6 | # Create a "steps" variable 7 | steps = 10 8 | 9 | # Repeat "half-steps" times 10 | for i in range(int(steps/2)): 11 | 12 | # Repeat 4 times (for 4 sides) 13 | for i in range(4): 14 | # Move the turtle forward "steps" steps 15 | pyr.forward(steps) 16 | # Make the turtle turn right 90 degrees 17 | pyr.right(90) 18 | 19 | # Make the turtle go up by one and inside the square by one, 20 | # each time returning to the original heading 21 | pyr.forward(1) 22 | pyr.right(90) 23 | pyr.forward(1) 24 | pyr.left(90) 25 | pyr.up(90) 26 | pyr.forward(1) 27 | pyr.down(90) 28 | 29 | # Decrease steps by two (one for each end of the sides) 30 | steps = steps - 2 31 | -------------------------------------------------------------------------------- /recipes/turtle_circles.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | # Create a Turtle object 4 | uga = Turtle([wool, 0]) 5 | # Make our Turtle rotate up 90 degrees 6 | uga.up(90) 7 | 8 | # FOREVER 9 | while True: 10 | 11 | # Repeat the following instructions 12 times 12 | # because the wool block has 12 different colors 13 | for color in range(12): 14 | 15 | # Set the block that our Turtle will use to draw - especially the color subtype 16 | uga.penblock([wool, color]) 17 | 18 | # Repeat 18 times 19 | for i in range(18): 20 | # Move our Turtle forward 21 | uga.forward(5) 22 | # Make our Turtle turn up of 20 degrees (18 * 20 = 360) 23 | uga.up(20) 24 | 25 | # When a circle is complete, let's rotate other 30 degrees 26 | # so that we are ready to repeat all these steps and draw 27 | # another circle in a different position 28 | uga.up(30) 29 | -------------------------------------------------------------------------------- /recipes/turtle_flowers.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | # Create a Turtle object 4 | kiki = Turtle([wool, random.randint(1, 12)]) 5 | # Set turtle speed 6 | kiki.speed(11) 7 | 8 | 9 | # Define how to make a quarter of a circle 10 | def circle_quarter(steps): 11 | for i in range(90): 12 | kiki.forward(steps) 13 | kiki.right(1) 14 | 15 | 16 | # Define how to make a petal 17 | def petal(size): 18 | circle_quarter(size) 19 | kiki.right(90) 20 | circle_quarter(size) 21 | kiki.right(90) 22 | 23 | 24 | # Define how to make a flower 25 | def flower(size, petals): 26 | for i in range(petals): 27 | petal(size) 28 | kiki.right(360 / petals) 29 | 30 | 31 | # Define how to make many flowers 32 | def flowers(amount): 33 | for i in range(amount): 34 | kiki.penblock([wool, random.randint(1, 12)]) 35 | flower(1, random.randint(3, 12)) 36 | kiki.penup() 37 | pos = where() 38 | kiki.goto(0, -1, 0) 39 | kiki.pendown() 40 | 41 | 42 | # Generate flowers calling the last function 43 | flowers(10) 44 | -------------------------------------------------------------------------------- /pycraft_minetest/event.py: -------------------------------------------------------------------------------- 1 | from . vec3 import Vec3 2 | 3 | class BlockEvent: 4 | """An Event related to blocks (e.g. placed, removed, hit)""" 5 | HIT = 0 6 | 7 | def __init__(self, type, x, y, z, face, entityId): 8 | self.type = type 9 | self.pos = Vec3(x, y, z) 10 | self.face = face 11 | self.entityId = entityId 12 | 13 | def __repr__(self): 14 | sType = { 15 | BlockEvent.HIT: "BlockEvent.HIT" 16 | }.get(self.type, "???") 17 | 18 | return "BlockEvent(%s, %d, %d, %d, %d, %d)"%( 19 | sType,self.pos.x,self.pos.y,self.pos.z,self.face,self.entityId); 20 | 21 | @staticmethod 22 | def Hit(x, y, z, face, entityId): 23 | return BlockEvent(BlockEvent.HIT, x, y, z, face, entityId) 24 | 25 | class ChatEvent: 26 | """An Event related to chat (e.g. posts)""" 27 | POST = 0 28 | 29 | def __init__(self, type, entityId, message): 30 | self.type = type 31 | self.entityId = entityId 32 | self.message = message 33 | 34 | def __repr__(self): 35 | sType = { 36 | ChatEvent.POST: "ChatEvent.POST" 37 | }.get(self.type, "???") 38 | 39 | return "ChatEvent(%s, %d, %s)"%( 40 | sType,self.entityId,self.message); 41 | 42 | @staticmethod 43 | def Post(entityId, message): 44 | return ChatEvent(ChatEvent.POST, entityId, message) 45 | 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pycraft library for Minecraft or Minetest 2 | pycraft_minetest icon 3 | Repository for the Pypi "pycraft_minetest" Python Package. 4 | 5 | Modified, simplified and improved libraries to code in python via Minecraft/Minetest. 6 | 7 | Based on the terrific idea and the original code of David Whale and Martin O'Hanlon (www.stuffaboutcode.com). 8 | 9 | Alessandro Norfo (ale.norfo@gmail.com) & Giuseppe Menegoz (gmenegoz@gmail.com). 10 | 11 | # Getting Started 12 | ## Install Python 13 | * If you are a beginner, we suggest to install [Thonny](https://thonny.org/), a simple editor that comes bundled with Python 3. 14 | 15 | ## Install Pycraft library 16 | * In Thonny, go to "Tools" menu -> "Manage Packages" 17 | * Now write "pycraft_minetest" in the resarch field 18 | * Clic on the "INSTALL" button 19 | 20 | ## Install the game and the Pycraft mod 21 | * For MINECRAFT follow these [instructions](https://github.com/gmenegoz/pycraft/blob/master/README.md) 22 | * For MINETEST follow these [instructions](https://github.com/sprintingkiwi/pycraft_mod/blob/master/README.md) 23 | 24 | ## Create your Python script and run it 25 | Now that the Pycraft environment is setted up you are ready to explore and play with Python in Minecraft/Minetest. 26 | 27 | You can learn how to use this library looking at the following examples: https://github.com/sprintingkiwi/pycraft_lib/tree/master/recipes 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # dotenv 85 | .env 86 | 87 | # virtualenv 88 | .venv 89 | venv/ 90 | ENV/ 91 | 92 | # Spyder project settings 93 | .spyderproject 94 | .spyproject 95 | 96 | # Rope project settings 97 | .ropeproject 98 | 99 | # mkdocs documentation 100 | /site 101 | 102 | # mypy 103 | .mypy_cache/ 104 | -------------------------------------------------------------------------------- /pycraft_minetest/entity.py: -------------------------------------------------------------------------------- 1 | ITEM = "Item" 2 | XPORB = "XPOrb" 3 | LEASHKNOT = "LeashKnot" 4 | PAINTING = "Painting" 5 | ARROW = "Arrow" 6 | SNOWBALL = "Snowball" 7 | FIREBALL = "Fireball" 8 | SMALLFIREBALL = "SmallFireball" 9 | THROWNENDERPEARL = "ThrownEnderpearl" 10 | EYEOFENDERSIGNAL = "EyeOfEnderSignal" 11 | THROWNPOTION = "ThrownPotion" 12 | THROWNEXPBOTTLE = "ThrownExpBottle" 13 | ITEMFRAME = "ItemFrame" 14 | WITHERSKULL = "WitherSkull" 15 | PRIMEDTNT = "PrimedTnt" 16 | FALLINGSAND = "FallingSand" 17 | FIREWORKSROCKETENTITY = "FireworksRocketEntity" 18 | ARMORSTAND = "ArmorStand" 19 | BOAT = "Boat" 20 | MINECARTRIDEABLE = "MinecartRideable" 21 | MINECARTCHEST = "MinecartChest" 22 | MINECARTFURNACE = "MinecartFurnace" 23 | MINECARTTNT = "MinecartTNT" 24 | MINECARTHOPPER = "MinecartHopper" 25 | MINECARTSPAWNER = "MinecartSpawner" 26 | MINECARTCOMMANDBLOCK = "MinecartCommandBlock" 27 | MOB = "Mob" 28 | MONSTER = "Monster" 29 | CREEPER = "Creeper" 30 | SKELETON = "Skeleton" 31 | SPIDER = "Spider" 32 | GIANT = "Giant" 33 | ZOMBIE = "Zombie" 34 | SLIME = "Slime" 35 | GHAST = "Ghast" 36 | PIGZOMBIE = "PigZombie" 37 | ENDERMAN = "Enderman" 38 | CAVESPIDER = "CaveSpider" 39 | SILVERFISH = "Silverfish" 40 | BLAZE = "Blaze" 41 | LAVASLIME = "LavaSlime" 42 | ENDERDRAGON = "EnderDragon" 43 | WITHERBOSS = "WitherBoss" 44 | BAT = "Bat" 45 | WITCH = "Witch" 46 | ENDERMITE = "Endermite" 47 | GUARDIAN = "Guardian" 48 | PIG = "Pig" 49 | SHEEP = "Sheep" 50 | COW = "Cow" 51 | CHICKEN = "Chicken" 52 | SQUID = "Squid" 53 | WOLF = "Wolf" 54 | MUSHROOMCOW = "MushroomCow" 55 | SNOWMAN = "SnowMan" 56 | OZELOT = "Ozelot" 57 | VILLAGERGOLEM = "VillagerGolem" 58 | HORSE = "EntityHorse" 59 | RABBIT = "Rabbit" 60 | VILLAGER = "Villager" 61 | ENDERCRYSTAL = "EnderCrystal" 62 | PLAYER = "(ThePlayer)" 63 | -------------------------------------------------------------------------------- /pycraft_minetest/mcpi_protocol_spec.txt: -------------------------------------------------------------------------------- 1 | MCPI-PROTOCOL 0.1 2 | 3 | OVERVIEW 4 | The mcpi-protocol enables an external process (program) to interact with a 5 | running instance of Minecraft Pi Edition. 6 | 7 | The protocol can easily be implemented and used from any programming language 8 | that has network socket support. The mcpi release includes api libraries (with 9 | source) for Python and Java. 10 | 11 | * Tcp-socket, port 4711 12 | * Commands are clear text lines (ASCII, LF terminated) 13 | 14 | 15 | DEFINITIONS 16 | x,y,z -- vector of three integers. 17 | xf,yf,zf -- vector of three floats. 18 | blockTypeId -- integer 0-108. 0 is air. 19 | blockData -- integer 0-15. Block data beyond the type, for example wool color. 20 | 21 | See: http://www.minecraftwiki.net/wiki/Data_values_(Pocket_Edition) 22 | 23 | 24 | COORDINATE SYSTEM 25 | Most coordinates are in the form of a three integer vector (x,y,z) which 26 | address a specific tile in the game world. (0,0,0) is the spawn point sea 27 | level. (X,Z) is the ground plane and Y is towards the sky. 28 | 29 | 30 | COMMANDS 31 | -- World -- 32 | world.getBlock(x,y,z) --> blockTypeId 33 | 34 | world.setBlock(x,y,z,blockTypeId) 35 | world.setBlock(x,y,z,blockTypeId,blockData) 36 | 37 | world.setBlocks(x1,y1,z1,x2,y2,z2,blockTypeId) 38 | world.setBlocks(x1,y1,z1,x2,y2,z2,blockTypeId,blockData) 39 | 40 | world.getHeight(x,z) --> Integer 41 | 42 | world.checkpoint.save() 43 | world.checkpoint.restore() 44 | 45 | TODO: skriva ut KEYs 46 | world.setting(KEY,0/1) 47 | 48 | chat.post(message) 49 | 50 | -- Camera -- 51 | camera.mode.setNormal() 52 | camera.mode.setThirdPerson() 53 | camera.mode.setFixed() 54 | camera.mode.setPos(x,y,z) 55 | 56 | -- Player -- 57 | player.getTile() --> x,y,z 58 | player.setTile(x,y,z) 59 | 60 | player.getPos() --> xf,yf,zf 61 | player.setPos(xf,yf,zf) 62 | 63 | -- Entities -- 64 | TBD 65 | 66 | 67 | -- Events -- 68 | events.block.hits() --> pos,surface,entityId|pos,surface,entityId|... (pos is x,y,z surface is x,y,z, entityId is int) 69 | events.clear 70 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | 3 | pos = where() 4 | chat(pos) 5 | 6 | # maze("maze1.csv") 7 | 8 | t = turtle(obsidian) 9 | t.forward(10) 10 | 11 | move(3, 10, 5) 12 | 13 | chat(where()) 14 | 15 | sphere(ice, y=-20) 16 | 17 | circle([wool, 5], direction="horizontal") 18 | 19 | line(gold, 0, 0, 0, 0, 50, 0) 20 | 21 | block(iron, y=3) 22 | 23 | blocks(wood, x=5, y=6, z=10) 24 | 25 | size = readnumber("tell the size...") 26 | 27 | cube(stone, size) 28 | 29 | text = readstring("say something...") 30 | 31 | chat("I said: " + text) 32 | 33 | pyramid(sandstone) 34 | 35 | polygon(obsidian, 12, 30) 36 | 37 | chat("Hello Minecraft!") 38 | 39 | color = 0 40 | 41 | uga = turtle([wool, color]) 42 | 43 | while True: 44 | 45 | for i in range(18): 46 | uga.forward(5) 47 | uga.up(20) 48 | uga.up(30) 49 | color += 1 50 | uga.penblock([wool, color % 12]) 51 | 52 | 53 | # GOLD in ICE 54 | # while True: 55 | # if over(ice): 56 | # chat("ice") 57 | # block(gold, y=-1) 58 | # if near(gold): 59 | # chat("gold nearby!") 60 | 61 | 62 | # TURTLE LOOP 63 | # uga = turtle(redstone) 64 | # passi = 2 65 | # while True: 66 | # uga.forward(passi) 67 | # uga.left(90) 68 | # passi = passi + 2 69 | 70 | # uga = turtle(redstone) 71 | # bea = turtle(beacon) 72 | # bea.setposition(0, 1, 0) 73 | # # col = turtle(beacon) 74 | # 75 | # while True: 76 | # uga.forward(1) 77 | # bea.forward(1) 78 | 79 | # uga = turtle(redstone) 80 | # bea = turtle(powered_rail) 81 | # bea.setposition(0, 1, 0) 82 | # # col = turtle(beacon) 83 | # 84 | # while True: 85 | # uga.forward(2) 86 | # bea.forward(1) 87 | 88 | 89 | 90 | # ANIMATE CUBE 91 | # x = pos.x 92 | # y = pos.y 93 | # z = pos.z 94 | # while True: 95 | # cube(ice, 5, x, y, z, absolute=True) 96 | # move(x-5, y+1, z+2, absolute=True) 97 | # time.sleep(0.1) 98 | # cube(air, 5, x, y, z, absolute=True) 99 | # x += 1 100 | 101 | 102 | -------------------------------------------------------------------------------- /recipes/clock.py: -------------------------------------------------------------------------------- 1 | from pycraft_minetest import * 2 | import datetime 3 | 4 | ov = 0 5 | mv = 0 6 | sv = 0 7 | pos = where() 8 | size = 10 9 | hoursblock = wood 10 | minutesblock = grass 11 | secondsblock = glowstone 12 | circle(gold, size + 2, y=-2, direction="horizontal") 13 | circle(gold, size + 2, y=-1, direction="horizontal") 14 | circle(gold, size + 2, direction="horizontal") 15 | 16 | while True: 17 | now = datetime.datetime.now() 18 | o = now.hour 19 | m = now.minute 20 | s = now.second 21 | if ov != o: 22 | angle_ov = ov * 30 23 | line(air, 24 | pos.x, 25 | pos.y - 2, 26 | pos.z, 27 | pos.x + int(size * math.cos(math.radians(angle_ov))), 28 | pos.y - 2, 29 | pos.z + int(size * math.sin(math.radians(angle_ov))), 30 | absolute=True) 31 | angle_o = o * 30 32 | line(hoursblock, 33 | pos.x, 34 | pos.y - 2, 35 | pos.z, 36 | pos.x + int(size * math.cos(math.radians(angle_o))), 37 | pos.y - 2, 38 | pos.z + int(size * math.sin(math.radians(angle_o))), 39 | absolute=True) 40 | ov = o 41 | if mv != m: 42 | angle_mv = mv * 6 43 | line(air, 44 | pos.x, 45 | pos.y - 1, 46 | pos.z, 47 | pos.x + int(size * math.cos(math.radians(angle_mv))), 48 | pos.y - 1, 49 | pos.z + int(size * math.sin(math.radians(angle_mv))), 50 | absolute=True) 51 | angle_m = m * 6 52 | line(minutesblock, 53 | pos.x, 54 | pos.y - 1, 55 | pos.z, 56 | pos.x + int(size * math.cos(math.radians(angle_m))), 57 | pos.y - 1, 58 | pos.z + int(size * math.sin(math.radians(angle_m))), 59 | absolute=True) 60 | mv = m 61 | if sv != s: 62 | chat(str(o) + " : " + str(m) + " : " + str(s)) 63 | angle_sv = sv * 6 64 | line(air, 65 | pos.x, 66 | pos.y, 67 | pos.z, 68 | pos.x + int(size * math.cos(math.radians(angle_sv))), 69 | pos.y, 70 | pos.z + int(size * math.sin(math.radians(angle_sv))), 71 | absolute=True) 72 | angle_s = s * 6 73 | line(secondsblock, 74 | pos.x, 75 | pos.y, 76 | pos.z, 77 | pos.x + int(size * math.cos(math.radians(angle_s))), 78 | pos.y, 79 | pos.z + int(size * math.sin(math.radians(angle_s))), 80 | absolute=True) 81 | sv = s 82 | -------------------------------------------------------------------------------- /pycraft_minetest/vec3.py: -------------------------------------------------------------------------------- 1 | class Vec3: 2 | def __init__(self, x=0, y=0, z=0): 3 | self.x = x 4 | self.y = y 5 | self.z = z 6 | 7 | def __add__(self, rhs): 8 | c = self.clone() 9 | c += rhs 10 | return c 11 | 12 | def __iadd__(self, rhs): 13 | self.x += rhs.x 14 | self.y += rhs.y 15 | self.z += rhs.z 16 | return self 17 | 18 | def length(self): 19 | return self.lengthSqr ** .5 20 | 21 | def lengthSqr(self): 22 | return self.x * self.x + self.y * self.y + self.z * self.z 23 | 24 | def __mul__(self, k): 25 | c = self.clone() 26 | c *= k 27 | return c 28 | 29 | def __imul__(self, k): 30 | self.x *= k 31 | self.y *= k 32 | self.z *= k 33 | return self 34 | 35 | def clone(self): 36 | return Vec3(self.x, self.y, self.z) 37 | 38 | def __neg__(self): 39 | return Vec3(-self.x, -self.y, -self.z) 40 | 41 | def __sub__(self, rhs): 42 | return self.__add__(-rhs) 43 | 44 | def __isub__(self, rhs): 45 | return self.__iadd__(-rhs) 46 | 47 | def __repr__(self): 48 | return "Vec3(%s,%s,%s)"%(self.x,self.y,self.z) 49 | 50 | def __iter__(self): 51 | return iter((self.x, self.y, self.z)) 52 | 53 | def _map(self, func): 54 | self.x = func(self.x) 55 | self.y = func(self.y) 56 | self.z = func(self.z) 57 | 58 | def __cmp__(self, rhs): 59 | dx = self.x - rhs.x 60 | if dx != 0: return dx 61 | dy = self.y - rhs.y 62 | if dy != 0: return dy 63 | dz = self.z - rhs.z 64 | if dz != 0: return dz 65 | return 0 66 | 67 | def iround(self): self._map(lambda v:int(v+0.5)) 68 | def ifloor(self): self._map(int) 69 | 70 | def rotateLeft(self): self.x, self.z = self.z, -self.x 71 | def rotateRight(self): self.x, self.z = -self.z, self.x 72 | 73 | def testVec3(): 74 | # Note: It's not testing everything 75 | 76 | # 1.1 Test initialization 77 | it = Vec3(1, -2, 3) 78 | assert it.x == 1 79 | assert it.y == -2 80 | assert it.z == 3 81 | 82 | assert it.x != -1 83 | assert it.y != +2 84 | assert it.z != -3 85 | 86 | # 2.1 Test cloning and equality 87 | clone = it.clone() 88 | assert it == clone 89 | it.x += 1 90 | assert it != clone 91 | 92 | # 3.1 Arithmetic 93 | a = Vec3(10, -3, 4) 94 | b = Vec3(-7, 1, 2) 95 | c = a + b 96 | assert c - a == b 97 | assert c - b == a 98 | assert a + a == a * 2 99 | 100 | assert a - a == Vec3(0,0,0) 101 | assert a + (-a) == Vec3(0,0,0) 102 | 103 | # Test repr 104 | e = eval(repr(it)) 105 | assert e == it 106 | 107 | if __name__ == "__main__": 108 | testVec3() 109 | -------------------------------------------------------------------------------- /pycraft_minetest/util.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import math 3 | import copy 4 | from . vec3 import Vec3 5 | 6 | def intFloor(*args): 7 | return [int(math.floor(x)) for x in flatten(args)] 8 | 9 | def flatten(l): 10 | for e in l: 11 | if isinstance(e, collections.abc.Iterable) and not isinstance(e, str): 12 | for ee in flatten(e): yield ee 13 | else: yield e 14 | 15 | 16 | # this is highly optimized to iterables consisting at base level of ints and floats only 17 | def floorFlatten(l): 18 | for e in l: 19 | if isinstance(e, int): 20 | yield str(e) 21 | elif isinstance(e, float): 22 | yield str(int(math.floor(e))) 23 | elif not e is None: 24 | for ee in floorFlatten(e): yield ee 25 | 26 | 27 | def flatten_parameters_to_string(l): 28 | return ",".join(map(str, flatten(l))) 29 | 30 | 31 | # return maximum of 2 values 32 | def MAX(a, b): 33 | if a > b: 34 | return a 35 | else: 36 | return b 37 | 38 | 39 | # return step 40 | def ZSGN(a): 41 | if a < 0: 42 | return -1 43 | elif a > 0: 44 | return 1 45 | elif a == 0: 46 | return 0 47 | 48 | 49 | def getLine(x1, y1, z1, x2, y2, z2): 50 | 51 | # list for vertices 52 | vertices = [] 53 | 54 | # if the 2 points are the same, return single vertice 55 | if (x1 == x2 and y1 == y2 and z1 == z2): 56 | vertices.append(Vec3(x1, y1, z1)) 57 | 58 | # else get all points in edge 59 | else: 60 | 61 | dx = x2 - x1 62 | dy = y2 - y1 63 | dz = z2 - z1 64 | 65 | ax = abs(dx) << 1 66 | ay = abs(dy) << 1 67 | az = abs(dz) << 1 68 | 69 | sx = ZSGN(dx) 70 | sy = ZSGN(dy) 71 | sz = ZSGN(dz) 72 | 73 | x = x1 74 | y = y1 75 | z = z1 76 | 77 | # x dominant 78 | if (ax >= MAX(ay, az)): 79 | yd = ay - (ax >> 1) 80 | zd = az - (ax >> 1) 81 | loop = True 82 | while(loop): 83 | vertices.append(Vec3(x, y, z)) 84 | if (x == x2): 85 | loop = False 86 | if (yd >= 0): 87 | y += sy 88 | yd -= ax 89 | if (zd >= 0): 90 | z += sz 91 | zd -= ax 92 | x += sx 93 | yd += ay 94 | zd += az 95 | # y dominant 96 | elif (ay >= MAX(ax, az)): 97 | xd = ax - (ay >> 1) 98 | zd = az - (ay >> 1) 99 | loop = True 100 | while(loop): 101 | vertices.append(Vec3(x, y, z)) 102 | if (y == y2): 103 | loop=False 104 | if (xd >= 0): 105 | x += sx 106 | xd -= ay 107 | if (zd >= 0): 108 | z += sz 109 | zd -= ay 110 | y += sy 111 | xd += ax 112 | zd += az 113 | # z dominant 114 | elif(az >= MAX(ax, ay)): 115 | xd = ax - (az >> 1) 116 | yd = ay - (az >> 1) 117 | loop = True 118 | while(loop): 119 | vertices.append(Vec3(x, y, z)) 120 | if (z == z2): 121 | loop=False 122 | if (xd >= 0): 123 | x += sx 124 | xd -= az 125 | if (yd >= 0): 126 | y += sy 127 | yd -= az 128 | z += sz 129 | xd += ax 130 | yd += ay 131 | 132 | return vertices 133 | 134 | #def drawPoint3d(self, x, y, z, blockType, blockData=0): 135 | #self.conn.send("world.setBlock", intFloor(x, y, z, blockType, blockData)) 136 | 137 | #def getHeight(self, *args): 138 | #"""Get the height of the world (x,z) => int""" 139 | #return int(self.conn.sendReceive("world.getHeight", intFloor(args))) 140 | 141 | 142 | # def drawVertices(self, vertices, blockType, blockData=0): 143 | # for vertex in vertices: 144 | # conn.send("world.setBlock", intFloor(vertex.x, 145 | # vertex.y, 146 | # vertex.z, 147 | # blockType, 148 | # blockData)) 149 | -------------------------------------------------------------------------------- /pycraft_minetest/connection.py: -------------------------------------------------------------------------------- 1 | 2 | import socket 3 | import select 4 | import sys 5 | import atexit 6 | import os 7 | import platform 8 | import base64 9 | from hashlib import md5 10 | from . util import flatten_parameters_to_string 11 | 12 | """ @author: Aron Nieminen, Mojang AB""" 13 | 14 | class RequestError(Exception): 15 | pass 16 | 17 | class Connection: 18 | """Connection to a Minecraft Pi game""" 19 | RequestFailed = "Fail" 20 | 21 | def __init__(self, address=None, port=None): 22 | self.windows = (platform.system() == "Windows" or platform.system().startswith("CYGWIN_NT")) 23 | if address==None: 24 | try: 25 | address = os.environ['MINECRAFT_API_HOST'] 26 | except KeyError: 27 | address = "localhost" 28 | if port==None: 29 | try: 30 | port = int(os.environ['MINECRAFT_API_PORT']) 31 | except KeyError: 32 | port = 4711 33 | if int(sys.version[0]) >= 3: 34 | self.send = self.send_python3 35 | self.send_flat = self.send_flat_python3 36 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 37 | self.socket.connect((address, port)) 38 | self.readFile = self.socket.makefile("r") 39 | self.lastSent = "" 40 | self.encoding = "cp437" # "utf-8" 41 | if self.windows: 42 | atexit.register(self.close) 43 | 44 | def __del__(self): 45 | if self.windows: 46 | self.close() 47 | try: 48 | atexit.unregister(self.close) 49 | except: 50 | pass 51 | 52 | def close(self): 53 | try: 54 | if self.windows: 55 | # ugly hack to block until all sending is completed 56 | self.sendReceive("world.getBlock",0,0,0) 57 | except: 58 | pass 59 | try: 60 | self.socket.close() 61 | except: 62 | pass 63 | 64 | @staticmethod 65 | def tohex(data): 66 | return "".join((hex(b) for b in data)) 67 | 68 | def authenticate(self, username, password): 69 | challenge = self.sendReceive("world.getBlock",0,0,0) 70 | if challenge.startswith("security.challenge "): 71 | salt = challenge[19:].rstrip() 72 | auth = md5(salt+":"+username+":"+password).hexdigest() 73 | self.send("security.authenticate", auth) 74 | 75 | def drain(self): 76 | """Drains the socket of incoming data""" 77 | while True: 78 | readable, _, _ = select.select([self.socket], [], [], 0.0) 79 | if not readable: 80 | break 81 | data = self.socket.recv(1500) 82 | if not data: 83 | self.socket.close() 84 | raise ValueError('Socket got closed') 85 | e = "Drained Data: <%s>\n"%data.strip() 86 | e += "Last Message: <%s>\n"%self.lastSent.strip() 87 | sys.stderr.write(e) 88 | 89 | def send(self, f, *data): 90 | """Sends data. Note that a trailing newline '\n' is added here""" 91 | s = "%s(%s)\n"%(f, flatten_parameters_to_string(data)) 92 | self.drain() 93 | self.lastSent = s 94 | self.socket.sendall(s) 95 | 96 | def send_python3(self, f, *data): 97 | """Sends data. Note that a trailing newline '\n' is added here""" 98 | s = "%s(%s)\n" % (f, flatten_parameters_to_string(data)) 99 | self.drain() 100 | self.lastSent = s 101 | self.socket.sendall(s.encode(self.encoding)) 102 | 103 | def send_flat(self, f, data): 104 | """Sends data. Note that a trailing newline '\n' is added here""" 105 | s = "%s(%s)\n" % (f, ",".join(data)) 106 | self.drain() 107 | self.lastSent = s 108 | self.socket.sendall(s) 109 | 110 | def send_flat_python3(self, f, data): 111 | """Sends data. Note that a trailing newline '\n' is added here""" 112 | s = "%s(%s)\n" % (f, ",".join(data)) 113 | self.drain() 114 | self.lastSent = s 115 | self.socket.sendall(s.encode(self.encoding)) 116 | 117 | def receive(self): 118 | """Receives data. Note that the trailing newline '\n' is trimmed""" 119 | s = self.readFile.readline().rstrip("\n") 120 | if s == Connection.RequestFailed: 121 | raise RequestError("%s failed" % self.lastSent.strip()) 122 | return s 123 | 124 | def sendReceive(self, *data): 125 | """Sends and receive data""" 126 | self.send(*data) 127 | return self.receive() 128 | 129 | def sendReceive_flat(self, f, data): 130 | """Sends and receive data""" 131 | self.send_flat(f, data) 132 | return self.receive() 133 | -------------------------------------------------------------------------------- /recipes/maze1.csv: -------------------------------------------------------------------------------- 1 | 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 2 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 3 | 1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1 4 | 1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1 5 | 1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1 6 | 1,1,0,1,0,1,1,1,1,2,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1 7 | 1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1 8 | 1,1,1,1,1,1,0,2,0,0,0,1,1,1,1,1,1,1,1,1,1,1,2,2,0,0,2,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1 9 | 1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,2,2,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1 10 | 1,0,1,1,1,1,0,2,2,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1 11 | 1,0,0,0,0,0,0,2,2,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 12 | 1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1 13 | 1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1 14 | 1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1 15 | 1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,2,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1 16 | 1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1 17 | 1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 18 | 0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 19 | 1,1,1,1,1,1,1,1,1,2,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,2,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1 20 | 1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1 21 | 1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1 22 | 1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1 23 | 1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1 24 | 1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1 25 | 1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1 26 | 1,0,1,1,1,1,0,2,2,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1 27 | 1,0,0,0,0,0,0,2,2,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 28 | 1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1 29 | 1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1 30 | 1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1 31 | 1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1 32 | 1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1 33 | 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 34 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1 35 | 1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,2,2,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,2,2,1,1,1,1,1,1,0,1,0,1,1,0,1 36 | 1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1 37 | 1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1 38 | 1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1 39 | 1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1 40 | 1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,2,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1 41 | 1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,2,2,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1 42 | 1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1 43 | 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 44 | 1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1 45 | 1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1 46 | 1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1 47 | 1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1 48 | 1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1 49 | 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 50 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 51 | 1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1 52 | 1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1 53 | 1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,1 54 | 1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1 55 | 1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1 56 | 1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1 57 | 1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1 58 | 1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1 59 | 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 60 | 1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1 61 | 1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1 62 | 1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1 63 | 1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1 64 | 1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1 65 | -------------------------------------------------------------------------------- /pycraft_minetest/blocklist.py: -------------------------------------------------------------------------------- 1 | from . import settings 2 | 3 | class Block: 4 | """Minecraft PI block description. Can be sent to Minecraft.setBlock/s""" 5 | def __init__(self, id, data=0, nbt=None): 6 | self.id = id 7 | self.data = data 8 | if nbt is not None and len(nbt)==0: 9 | self.nbt = None 10 | else: 11 | self.nbt = nbt 12 | 13 | def __eq__(self, rhs): 14 | try: 15 | return self.id == rhs.id and self.data == rhs.data and self.nbt == rhs.nbt 16 | except: 17 | return self.data == 0 and self.nbt is None and self.id == rhs 18 | 19 | def __ne__(self, rhs): 20 | return not self.__eq__(rhs) 21 | 22 | def __hash__(self): 23 | h = (self.id << 8) + self.data 24 | if self.nbt is not None: 25 | h ^= hash(self.nbt) 26 | 27 | def withData(self, data): 28 | return Block(self.id, data) 29 | 30 | def __iter__(self): 31 | """Allows a Block to be sent whenever id [and data] is needed""" 32 | if self.nbt is not None: 33 | return iter((self.id, self.data, self.nbt)) 34 | else: 35 | return iter((self.id, self.data)) 36 | 37 | def __repr__(self): 38 | if self.nbt is None: 39 | return "Block(%d, %d)"%(self.id, self.data) 40 | else: 41 | return "Block(%d, %d, %s)"%(self.id, self.data, repr(self.nbt)) 42 | 43 | 44 | 45 | AIR = Block(0) 46 | STONE = Block(1) 47 | GRASS = Block(2) 48 | DIRT = Block(3) 49 | COBBLESTONE = Block(4) 50 | WOOD_PLANKS = Block(5) 51 | SAPLING = Block(6) 52 | BEDROCK = Block(7) 53 | WATER_FLOWING = Block(8) 54 | WATER = WATER_FLOWING 55 | WATER_STATIONARY = Block(9) 56 | LAVA_FLOWING = Block(10) 57 | LAVA = LAVA_FLOWING 58 | LAVA_STATIONARY = Block(11) 59 | SAND = Block(12) 60 | GRAVEL = Block(13) 61 | GOLD_ORE = Block(14) 62 | IRON_ORE = Block(15) 63 | COAL_ORE = Block(16) 64 | WOOD = Block(17) 65 | LEAVES = Block(18) 66 | GLASS = Block(20) 67 | LAPIS_LAZULI_ORE = Block(21) 68 | LAPIS_LAZULI_BLOCK = Block(22) 69 | SANDSTONE = Block(24) 70 | BED = Block(26) 71 | COBWEB = Block(30) 72 | GRASS_TALL = Block(31) 73 | WOOL = Block(35) 74 | FLOWER_YELLOW = Block(37) 75 | FLOWER_CYAN = Block(38) 76 | MUSHROOM_BROWN = Block(39) 77 | MUSHROOM_RED = Block(40) 78 | GOLD_BLOCK = Block(41) 79 | IRON_BLOCK = Block(42) 80 | STONE_SLAB_DOUBLE = Block(43) 81 | STONE_SLAB = Block(44) 82 | BRICK_BLOCK = Block(45) 83 | TNT = Block(46) 84 | BOOKSHELF = Block(47) 85 | MOSS_STONE = Block(48) 86 | OBSIDIAN = Block(49) 87 | TORCH = Block(50) 88 | FIRE = Block(51) 89 | STAIRS_WOOD = Block(53) 90 | CHEST = Block(54) 91 | DIAMOND_ORE = Block(56) 92 | DIAMOND_BLOCK = Block(57) 93 | CRAFTING_TABLE = Block(58) 94 | FARMLAND = Block(60) 95 | FURNACE_INACTIVE = Block(61) 96 | FURNACE_ACTIVE = Block(62) 97 | DOOR_WOOD = Block(64) 98 | LADDER = Block(65) 99 | STAIRS_COBBLESTONE = Block(67) 100 | DOOR_IRON = Block(71) 101 | REDSTONE_ORE = Block(73) 102 | STONE_BUTTON = Block(77) 103 | SNOW = Block(78) 104 | ICE = Block(79) 105 | SNOW_BLOCK = Block(80) 106 | CACTUS = Block(81) 107 | CLAY = Block(82) 108 | SUGAR_CANE = Block(83) 109 | FENCE = Block(85) 110 | GLOWSTONE_BLOCK = Block(89) 111 | BEDROCK_INVISIBLE = Block(95) 112 | if settings.isPE: 113 | STAINED_GLASS = WOOL 114 | else: 115 | STAINED_GLASS = Block(95) 116 | STONE_BRICK = Block(98) 117 | GLASS_PANE = Block(102) 118 | MELON = Block(103) 119 | FENCE_GATE = Block(107) 120 | WOOD_BUTTON = Block(143) 121 | REDSTONE_BLOCK = Block(152) 122 | QUARTZ_BLOCK = Block(155) 123 | 124 | if settings.isPE: 125 | HARDENED_CLAY_STAINED = WOOL 126 | else: 127 | HARDENED_CLAY_STAINED = Block(159) 128 | 129 | if settings.isPE: 130 | SEA_LANTERN = Block(246) # glowing obsidian 131 | else: 132 | SEA_LANTERN = Block(169) 133 | 134 | CARPET = Block(171) 135 | COAL_BLOCK = Block(173) 136 | 137 | if settings.isPE: 138 | GLOWING_OBSIDIAN = Block(246) 139 | NETHER_REACTOR_CORE = Block(247) 140 | REDSTONE_LAMP_INACTIVE = OBSIDIAN 141 | REDSTONE_LAMP_ACTIVE = GLOWING_OBSIDIAN 142 | else: 143 | GLOWING_OBSIDIAN = SEA_LANTERN 144 | NETHER_REACTOR_CORE = SEA_LANTERN 145 | REDSTONE_LAMP_INACTIVE = Block(123) 146 | REDSTONE_LAMP_ACTIVE = Block(124) 147 | 148 | SUNFLOWER = Block(175,0) 149 | LILAC = Block(175,1) 150 | DOUBLE_TALLGRASS = Block(175,2) 151 | LARGE_FERN = Block(175,3) 152 | ROSE_BUSH = Block(175,4) 153 | PEONY = Block(175,5) 154 | 155 | WOOL_WHITE = Block(WOOL.id, 0) 156 | WOOL_ORANGE = Block(WOOL.id, 1) 157 | WOOL_MAGENTA = Block(WOOL.id, 2) 158 | WOOL_LIGHT_BLUE = Block(WOOL.id, 3) 159 | WOOL_YELLOW = Block(WOOL.id, 4) 160 | WOOL_LIME = Block(WOOL.id, 5) 161 | WOOL_PINK = Block(WOOL.id, 6) 162 | WOOL_GRAY = Block(WOOL.id, 7) 163 | WOOL_LIGHT_GRAY = Block(WOOL.id, 8) 164 | WOOL_CYAN = Block(WOOL.id, 9) 165 | WOOL_PURPLE = Block(WOOL.id, 10) 166 | WOOL_BLUE = Block(WOOL.id, 11) 167 | WOOL_BROWN = Block(WOOL.id, 12) 168 | WOOL_GREEN = Block(WOOL.id, 13) 169 | WOOL_RED = Block(WOOL.id, 14) 170 | WOOL_BLACK = Block(WOOL.id, 15) 171 | 172 | CARPET_WHITE = Block(CARPET.id, 0) 173 | CARPET_ORANGE = Block(CARPET.id, 1) 174 | CARPET_MAGENTA = Block(CARPET.id, 2) 175 | CARPET_LIGHT_BLUE = Block(CARPET.id, 3) 176 | CARPET_YELLOW = Block(CARPET.id, 4) 177 | CARPET_LIME = Block(CARPET.id, 5) 178 | CARPET_PINK = Block(CARPET.id, 6) 179 | CARPET_GRAY = Block(CARPET.id, 7) 180 | CARPET_LIGHT_GRAY = Block(CARPET.id, 8) 181 | CARPET_CYAN = Block(CARPET.id, 9) 182 | CARPET_PURPLE = Block(CARPET.id, 10) 183 | CARPET_BLUE = Block(CARPET.id, 11) 184 | CARPET_BROWN = Block(CARPET.id, 12) 185 | CARPET_GREEN = Block(CARPET.id, 13) 186 | CARPET_RED = Block(CARPET.id, 14) 187 | CARPET_BLACK = Block(CARPET.id, 15) 188 | 189 | STAINED_GLASS_WHITE = Block(STAINED_GLASS.id, 0) 190 | STAINED_GLASS_ORANGE = Block(STAINED_GLASS.id, 1) 191 | STAINED_GLASS_MAGENTA = Block(STAINED_GLASS.id, 2) 192 | STAINED_GLASS_LIGHT_BLUE = Block(STAINED_GLASS.id, 3) 193 | STAINED_GLASS_YELLOW = Block(STAINED_GLASS.id, 4) 194 | STAINED_GLASS_LIME = Block(STAINED_GLASS.id, 5) 195 | STAINED_GLASS_PINK = Block(STAINED_GLASS.id, 6) 196 | STAINED_GLASS_GRAY = Block(STAINED_GLASS.id, 7) 197 | STAINED_GLASS_LIGHT_GRAY = Block(STAINED_GLASS.id, 8) 198 | STAINED_GLASS_CYAN = Block(STAINED_GLASS.id, 9) 199 | STAINED_GLASS_PURPLE = Block(STAINED_GLASS.id, 10) 200 | STAINED_GLASS_BLUE = Block(STAINED_GLASS.id, 11) 201 | STAINED_GLASS_BROWN = Block(STAINED_GLASS.id, 12) 202 | STAINED_GLASS_GREEN = Block(STAINED_GLASS.id, 13) 203 | STAINED_GLASS_RED = Block(STAINED_GLASS.id, 14) 204 | STAINED_GLASS_BLACK = Block(STAINED_GLASS.id, 15) 205 | 206 | HARDENED_CLAY_STAINED_WHITE = Block(HARDENED_CLAY_STAINED.id, 0) 207 | HARDENED_CLAY_STAINED_ORANGE = Block(HARDENED_CLAY_STAINED.id, 1) 208 | HARDENED_CLAY_STAINED_MAGENTA = Block(HARDENED_CLAY_STAINED.id, 2) 209 | HARDENED_CLAY_STAINED_LIGHT_BLUE = Block(HARDENED_CLAY_STAINED.id, 3) 210 | HARDENED_CLAY_STAINED_YELLOW = Block(HARDENED_CLAY_STAINED.id, 4) 211 | HARDENED_CLAY_STAINED_LIME = Block(HARDENED_CLAY_STAINED.id, 5) 212 | HARDENED_CLAY_STAINED_PINK = Block(HARDENED_CLAY_STAINED.id, 6) 213 | HARDENED_CLAY_STAINED_GRAY = Block(HARDENED_CLAY_STAINED.id, 7) 214 | HARDENED_CLAY_STAINED_LIGHT_GRAY = Block(HARDENED_CLAY_STAINED.id, 8) 215 | HARDENED_CLAY_STAINED_CYAN = Block(HARDENED_CLAY_STAINED.id, 9) 216 | HARDENED_CLAY_STAINED_PURPLE = Block(HARDENED_CLAY_STAINED.id, 10) 217 | HARDENED_CLAY_STAINED_BLUE = Block(HARDENED_CLAY_STAINED.id, 11) 218 | HARDENED_CLAY_STAINED_BROWN = Block(HARDENED_CLAY_STAINED.id, 12) 219 | HARDENED_CLAY_STAINED_GREEN = Block(HARDENED_CLAY_STAINED.id, 13) 220 | HARDENED_CLAY_STAINED_RED = Block(HARDENED_CLAY_STAINED.id, 14) 221 | HARDENED_CLAY_STAINED_BLACK = Block(HARDENED_CLAY_STAINED.id, 15) 222 | 223 | LEAVES_OAK_DECAYABLE = Block(LEAVES.id, 0) 224 | LEAVES_SPRUCE_DECAYABLE = Block(LEAVES.id, 1) 225 | LEAVES_BIRCH_DECAYABLE = Block(LEAVES.id, 2) 226 | LEAVES_JUNGLE_DECAYABLE = Block(LEAVES.id, 3) 227 | LEAVES_OAK_PERMANENT = Block(LEAVES.id, 4) 228 | LEAVES_SPRUCE_PERMANENT = Block(LEAVES.id, 5) 229 | LEAVES_BIRCH_PERMANENT = Block(LEAVES.id, 6) 230 | LEAVES_JUNGLE_PERMANENT = Block(LEAVES.id, 7) 231 | if settings.isPE: 232 | LEAVES_ACACIA_DECAYABLE = Block(161,0) 233 | LEAVES_DARK_OAK_DECAYABLE = Block(161,1) 234 | LEAVES_ACACIA_PERMANENT = Block(161,2) 235 | LEAVES_DARK_OAK_PERMANENT = Block(161,3) 236 | else: 237 | LEAVES_ACACIA_DECAYABLE = LEAVES_OAK_DECAYABLE 238 | LEAVES_DARK_OAK_DECAYABLE = LEAVES_JUNGLE_DECAYABLE 239 | LEAVES_ACACIA_PERMANENT = LEAVES_OAK_PERMANENT 240 | LEAVES_DARK_OAK_PERMANENT = LEAVES_JUNGLE_PERMANENT 241 | -------------------------------------------------------------------------------- /pycraft_minetest/minecraft.py: -------------------------------------------------------------------------------- 1 | from connection import Connection,RequestError 2 | from vec3 import Vec3 3 | from event import BlockEvent,ChatEvent 4 | from block import Block 5 | import math 6 | from os import environ 7 | from util import flatten,floorFlatten 8 | import security 9 | 10 | """ Minecraft PI low level api v0.1_1 11 | 12 | Note: many methods have the parameter *arg. This solution makes it 13 | simple to allow different types, and variable number of arguments. 14 | The actual magic is a mix of flatten_parameters() and __iter__. Example: 15 | A Cube class could implement __iter__ to work in Minecraft.setBlocks(c, id). 16 | 17 | (Because of this, it's possible to "erase" arguments. CmdPlayer removes 18 | entityId, by injecting [] that flattens to nothing) 19 | 20 | @author: Aron Nieminen, Mojang AB""" 21 | 22 | 23 | #def strFloor(*args): 24 | # return [str(int(math.floor(x))) for x in flatten(args)] 25 | 26 | def fixPipe(s): 27 | return s.replace('|', '|').replace('&','&') 28 | 29 | def stringToBlockWithNBT(s, pipeFix = False): 30 | data = s.split(",") 31 | id = int(data[0]) 32 | if len(data) <= 1: 33 | return Block(id) 34 | elif len(data) <= 2: 35 | return Block(id,int(data[1])) 36 | else: 37 | nbt = ','.join(data[2:]) 38 | if pipeFix: 39 | nbt = fixPipe(nbt) 40 | return Block(id,int(data[1]),nbt) 41 | 42 | class CmdPositioner: 43 | """Methods for setting and getting positions""" 44 | def __init__(self, connection, packagePrefix): 45 | self.conn = connection 46 | self.pkg = packagePrefix 47 | 48 | def getBlock(self, *args): 49 | """Get block (x,y,z) => id:int""" 50 | return int(self.conn.sendReceive_flat("world.getBlock", floorFlatten(args))) 51 | 52 | def getPitch(self, id): 53 | """Get entity direction (entityId:int) => Vec3""" 54 | s = self.conn.sendReceive(self.pkg + ".getPitch", id) 55 | return float(s) 56 | 57 | def getRotation(self, id): 58 | """Get entity direction (entityId:int) => Vec3""" 59 | s = self.conn.sendReceive(self.pkg + ".getRotation", id) 60 | return float(s) 61 | 62 | def getDirection(self, id): 63 | """Get entity direction (entityId:int) => Vec3""" 64 | s = self.conn.sendReceive(self.pkg + ".getDirection", id) 65 | return Vec3(*map(float, s.split(","))) 66 | 67 | def getPos(self, id): 68 | """Get entity position (entityId:int) => Vec3""" 69 | s = self.conn.sendReceive(self.pkg + ".getPos", id) 70 | return Vec3(*map(float, s.split(","))) 71 | 72 | def setPos(self, id, *args): 73 | """Set entity position (entityId:int, x,y,z)""" 74 | self.conn.send(self.pkg + ".setPos", id, args) 75 | 76 | def setDirection(self, id, *args): 77 | """Set entity pitch (entityId:int, x,y,z)""" 78 | self.conn.send(self.pkg + ".setDirection", id, args) 79 | 80 | def setRotation(self, id, *args): 81 | """Set entity rotation (entityId:int, angle)""" 82 | self.conn.send(self.pkg + ".setRotation", id, args) 83 | 84 | def setPitch(self, id, *args): 85 | """Set entity pitch (entityId:int, angle)""" 86 | self.conn.send(self.pkg + ".setPitch", id, args) 87 | 88 | def getTilePos(self, id, *args): 89 | """Get entity tile position (entityId:int) => Vec3""" 90 | s = self.conn.sendReceive(self.pkg + ".getTile", id) 91 | return Vec3(*map(int, s.split(","))) 92 | 93 | def setTilePos(self, id, *args): 94 | """Set entity tile position (entityId:int) => Vec3""" 95 | self.conn.send(self.pkg + ".setTile", id, floorFlatten(*args)) 96 | 97 | def setting(self, setting, status): 98 | """Set a player setting (setting, status). keys: autojump""" 99 | self.conn.send(self.pkg + ".setting", setting, 1 if bool(status) else 0) 100 | 101 | 102 | class CmdEntity(CmdPositioner): 103 | """Methods for entities""" 104 | def __init__(self, connection): 105 | CmdPositioner.__init__(self, connection, "entity") 106 | 107 | 108 | class CmdPlayer(CmdPositioner): 109 | """Methods for the host (Raspberry Pi) player""" 110 | def __init__(self, connection, playerId=()): 111 | CmdPositioner.__init__(self, connection, "player" if playerId==() else "entity") 112 | self.id = playerId 113 | self.conn = connection 114 | 115 | def getDirection(self): 116 | return CmdPositioner.getDirection(self, self.id) 117 | def getPitch(self): 118 | return CmdPositioner.getPitch(self, self.id) 119 | def getRotation(self): 120 | return CmdPositioner.getRotation(self, self.id) 121 | def setPitch(self, *args): 122 | return CmdPositioner.setPitch(self, self.id, args) 123 | def setRotation(self, *args): 124 | return CmdPositioner.setRotation(self, self.id, args) 125 | def setDirection(self, *args): 126 | return CmdPositioner.setDirection(self, self.id, args) 127 | def getRotation(self): 128 | return CmdPositioner.getRotation(self, self.id) 129 | def getPos(self): 130 | return CmdPositioner.getPos(self, self.id) 131 | def setPos(self, *args): 132 | return CmdPositioner.setPos(self, self.id, args) 133 | def getTilePos(self): 134 | return CmdPositioner.getTilePos(self, self.id) 135 | def setTilePos(self, *args): 136 | return CmdPositioner.setTilePos(self, self.id, args) 137 | 138 | class CmdCamera: 139 | def __init__(self, connection): 140 | self.conn = connection 141 | 142 | def setNormal(self, *args): 143 | """Set camera mode to normal Minecraft view ([entityId])""" 144 | self.conn.send("camera.mode.setNormal", args) 145 | 146 | def setFixed(self): 147 | """Set camera mode to fixed view""" 148 | self.conn.send("camera.mode.setFixed") 149 | 150 | def setFollow(self, *args): 151 | """Set camera mode to follow an entity ([entityId])""" 152 | self.conn.send("camera.mode.setFollow", args) 153 | 154 | def setPos(self, *args): 155 | """Set camera entity position (x,y,z)""" 156 | self.conn.send("camera.setPos", args) 157 | 158 | 159 | class CmdEvents: 160 | """Events""" 161 | def __init__(self, connection): 162 | self.conn = connection 163 | 164 | def clearAll(self): 165 | """Clear all old events""" 166 | self.conn.send("events.clear") 167 | 168 | def pollBlockHits(self): 169 | """Only triggered by sword => [BlockEvent]""" 170 | s = self.conn.sendReceive("events.block.hits") 171 | events = [e for e in s.split("|") if e] 172 | return [BlockEvent.Hit(*map(int, e.split(","))) for e in events] 173 | 174 | def pollChatPosts(self): 175 | """Triggered by posts to chat => [ChatEvent]""" 176 | s = self.conn.sendReceive("events.chat.posts") 177 | events = [fixPipe(e) for e in s.split("|") if e] 178 | return [ChatEvent.Post(int(e[:e.find(",")]), e[e.find(",") + 1:]) for e in events] 179 | 180 | class Minecraft: 181 | """The main class to interact with a running instance of Minecraft Pi.""" 182 | 183 | def __init__(self, connection=None, autoId=True): 184 | if connection: 185 | self.conn = connection 186 | else: 187 | self.conn = Connection() 188 | 189 | if security.AUTHENTICATION_USERNAME and security.AUTHENTICATION_PASSWORD: 190 | self.conn.authenticate(security.AUTHENTICATION_USERNAME, security.AUTHENTICATION_PASSWORD) 191 | 192 | self.camera = CmdCamera(self.conn) 193 | self.entity = CmdEntity(self.conn) 194 | 195 | self.playerId = None 196 | 197 | if autoId: 198 | try: 199 | self.playerId = int(environ['MINECRAFT_PLAYER_ID']) 200 | self.player = CmdPlayer(self.conn,playerId=self.playerId) 201 | except: 202 | try: 203 | self.playerId = self.getPlayerId(environ['MINECRAFT_PLAYER_NAME']) 204 | self.player = CmdPlayer(self.conn,playerId=self.playerId) 205 | except: 206 | if security.AUTHENTICATION_USERNAME: 207 | try: 208 | self.playerId = self.getPlayerId(security.AUTHENTICATION_USERNAME) 209 | self.player = CmdPlayer(self.conn,playerId=self.playerId) 210 | except: 211 | self.player = CmdPlayer(self.conn) 212 | else: 213 | self.player = CmdPlayer(self.conn) 214 | else: 215 | self.player = CmdPlayer(self.conn) 216 | 217 | self.events = CmdEvents(self.conn) 218 | self.enabledNBT = False 219 | 220 | 221 | def spawnEntity(self, *args): 222 | """Spawn entity (type,x,y,z,tags) and get its id => id:int""" 223 | return int(self.conn.sendReceive("world.spawnEntity", args)) 224 | 225 | def removeEntity(self, *args): 226 | """Remove entity (id)""" 227 | self.conn.send("world.removeEntity", args) 228 | 229 | def getBlock(self, *args): 230 | """Get block (x,y,z) => id:int""" 231 | return int(self.conn.sendReceive_flat("world.getBlock", floorFlatten(args))) 232 | 233 | def getBlockWithData(self, *args): 234 | """Get block with data (x,y,z) => Block""" 235 | ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args)) 236 | return Block(*map(int, ans.split(",")[:2])) 237 | 238 | def getBlockWithNBT(self, *args): 239 | """ 240 | Get block with data and nbt (x,y,z) => Block (if no NBT) or (Block,nbt) 241 | For this to work, you first need to do setting("include_nbt_with_data",1) 242 | """ 243 | if not self.enabledNBT: 244 | self.setting("include_nbt_with_data",1) 245 | self.enabledNBT = True 246 | try: 247 | ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args)) 248 | except RequestError: 249 | # retry in case we had a Fail from the setting 250 | ans = self.conn.receive() 251 | else: 252 | ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args)) 253 | return stringToBlockWithNBT(ans) 254 | """ 255 | @TODO 256 | """ 257 | 258 | def fallbackGetCuboid(self, getBlock, *args): 259 | (x0,y0,z0,x1,y1,z1) = map(lambda x:int(math.floor(float(x))), flatten(args)) 260 | out = [] 261 | for y in range(min(y0,y1),max(y0,y1)+1): 262 | for x in range(min(x0,x1),max(x0,x1)+1): 263 | for z in range(min(z0,z1),max(z0,z1)+1): 264 | out.append(getBlock(x,y,z)) 265 | return out 266 | 267 | def fallbackGetBlocksWithData(self, *args): 268 | return self.fallbackGetCuboid(self.getBlockWithData, args) 269 | 270 | def fallbackGetBlocks(self, *args): 271 | return self.fallbackGetCuboid(self.getBlock, args) 272 | 273 | def fallbackGetBlocksWithNBT(self, *args): 274 | return self.fallbackGetCuboid(self.getBlockWithNBT, args) 275 | 276 | def getBlocks(self, *args): 277 | """ 278 | Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [id:int] 279 | Packed with a y-loop, x-loop, z-loop, in this order. 280 | """ 281 | try: 282 | ans = self.conn.sendReceive_flat("world.getBlocks", floorFlatten(args)) 283 | return map(int, ans.split(",")) 284 | except: 285 | self.getBlocks = self.fallbackGetBlocks 286 | return self.fallbackGetBlocks(*args) 287 | 288 | def getBlocksWithData(self, *args): 289 | """Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [Block(id:int, meta:int)]""" 290 | try: 291 | ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args)) 292 | return [Block(*map(int, x.split(",")[:2])) for x in ans.split("|")] 293 | except: 294 | self.getBlocksWithData = self.fallbackGetBlocksWithData 295 | return self.fallbackGetBlocksWithData(*args) 296 | 297 | def getBlocksWithNBT(self, *args): 298 | """Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [Block(id, meta, nbt)]""" 299 | try: 300 | if not self.enabledNBT: 301 | self.setting("include_nbt_with_data",1) 302 | self.enabledNBT = True 303 | try: 304 | ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args)) 305 | except RequestError: 306 | # retry in case we had a Fail from the setting 307 | ans = self.conn.receive() 308 | else: 309 | ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args)) 310 | ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args)) 311 | return [stringToBlockWithNBT(x, pipeFix = True) for x in ans.split("|")] 312 | except: 313 | self.getBlocksWithNBT = self.fallbackGetBlocksWithNBT 314 | return self.fallbackGetBlocksWithNBT(*args) 315 | 316 | # must have no NBT tags in Block instance 317 | def setBlock(self, *args): 318 | """Set block (x,y,z,id,[data])""" 319 | self.conn.send_flat("world.setBlock", floorFlatten(args)) 320 | 321 | def setBlockWithNBT(self, *args): 322 | """Set block (x,y,z,id,data,nbt)""" 323 | data = list(flatten(args)) 324 | self.conn.send_flat("world.setBlock", list(floorFlatten(data[:5]))+data[5:]) 325 | 326 | # must have no NBT tags in Block instance 327 | def setBlocks(self, *args): 328 | """Set a cuboid of blocks (x0,y0,z0,x1,y1,z1,id,[data])""" 329 | self.conn.send_flat("world.setBlocks", floorFlatten(args)) 330 | 331 | def setBlocksWithNBT(self, *args): 332 | """Set a cuboid of blocks (x0,y0,z0,x1,y1,z1,id,data,nbt)""" 333 | data = list(flatten(args)) 334 | self.conn.send_flat("world.setBlocks", list(floorFlatten(data[:8]))+data[8:]) 335 | 336 | def getHeight(self, *args): 337 | """Get the height of the world (x,z) => int""" 338 | return int(self.conn.sendReceive_flat("world.getHeight", floorFlatten(args))) 339 | 340 | def getPlayerId(self, *args): 341 | """Get the id of the current player""" 342 | a = tuple(flatten(args)) 343 | if self.playerId is not None and len(a) == 0: 344 | return self.playerId 345 | else: 346 | return int(self.conn.sendReceive_flat("world.getPlayerId", flatten(args))) 347 | 348 | def getPlayerEntityIds(self): 349 | """Get the entity ids of the connected players => [id:int]""" 350 | ids = self.conn.sendReceive("world.getPlayerIds") 351 | return map(int, ids.split("|")) 352 | 353 | def saveCheckpoint(self): 354 | """Save a checkpoint that can be used for restoring the world""" 355 | self.conn.send("world.checkpoint.save") 356 | 357 | def restoreCheckpoint(self): 358 | """Restore the world state to the checkpoint""" 359 | self.conn.send("world.checkpoint.restore") 360 | 361 | def postToChat(self, msg): 362 | """Post a message to the game chat""" 363 | self.conn.send("chat.post", msg) 364 | 365 | def setting(self, setting, status): 366 | """Set a world setting (setting, status). keys: world_immutable, nametags_visible""" 367 | self.conn.send("world.setting", setting, 1 if bool(status) else 0) 368 | 369 | @staticmethod 370 | def create(address = None, port = None): 371 | return Minecraft(Connection(address, port)) 372 | 373 | 374 | if __name__ == "__main__": 375 | mc = Minecraft.create() 376 | mc.postToChat("Hello, Minecraft!") 377 | -------------------------------------------------------------------------------- /pycraft_minetest/nbt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Handle the NBT (Named Binary Tag) data format 3 | 4 | Copyright (c) 2010-2013 Thomas Woolford and contributors 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | """ 24 | 25 | from struct import Struct, error as StructError 26 | from gzip import GzipFile 27 | import zlib 28 | from collections import MutableMapping, MutableSequence, Sequence 29 | import os, io 30 | 31 | try: 32 | unicode 33 | basestring 34 | except NameError: 35 | unicode = str # compatibility for Python 3 36 | basestring = str # compatibility for Python 3 37 | 38 | 39 | TAG_END = 0 40 | TAG_BYTE = 1 41 | TAG_SHORT = 2 42 | TAG_INT = 3 43 | TAG_LONG = 4 44 | TAG_FLOAT = 5 45 | TAG_DOUBLE = 6 46 | TAG_BYTE_ARRAY = 7 47 | TAG_STRING = 8 48 | TAG_LIST = 9 49 | TAG_COMPOUND = 10 50 | TAG_INT_ARRAY = 11 51 | 52 | class MalformedFileError(Exception): 53 | """Exception raised on parse error.""" 54 | pass 55 | 56 | class TAG(object): 57 | """TAG, a variable with an intrinsic name.""" 58 | id = None 59 | 60 | def __init__(self, value=None, name=None): 61 | self.name = name 62 | self.value = value 63 | 64 | #Parsers and Generators 65 | def _parse_buffer(self, buffer): 66 | raise NotImplementedError(self.__class__.__name__) 67 | 68 | def _render_buffer(self, buffer): 69 | raise NotImplementedError(self.__class__.__name__) 70 | 71 | #Printing and Formatting of tree 72 | def tag_info(self): 73 | """Return Unicode string with class, name and unnested value.""" 74 | return self.__class__.__name__ + \ 75 | ('(%r)' % self.name if self.name else "") + \ 76 | ": " + self.valuestr() 77 | def valuestr(self): 78 | """Return Unicode string of unnested value. For iterators, this returns a summary.""" 79 | return unicode(self.value) 80 | 81 | def pretty_tree(self, indent=0): 82 | """Return formated Unicode string of self, where iterable items are recursively listed in detail.""" 83 | return ("\t"*indent) + self.tag_info() 84 | 85 | # Python 2 compatibility; Python 3 uses __str__ instead. 86 | def __unicode__(self): 87 | """Return a unicode string with the result in human readable format. Unlike valuestr(), the result is recursive for iterators till at least one level deep.""" 88 | return unicode(self.value) 89 | 90 | def __str__(self): 91 | """Return a string (ascii formated for Python 2, unicode for Python 3) with the result in human readable format. Unlike valuestr(), the result is recursive for iterators till at least one level deep.""" 92 | return str(self.value) 93 | # Unlike regular iterators, __repr__() is not recursive. 94 | # Use pretty_tree for recursive results. 95 | # iterators should use __repr__ or tag_info for each item, like regular iterators 96 | def __repr__(self): 97 | """Return a string (ascii formated for Python 2, unicode for Python 3) describing the class, name and id for debugging purposes.""" 98 | return "<%s(%r) at 0x%x>" % (self.__class__.__name__,self.name,id(self)) 99 | 100 | class _TAG_Numeric(TAG): 101 | """_TAG_Numeric, comparable to int with an intrinsic name""" 102 | def __init__(self, value=None, name=None, buffer=None): 103 | super(_TAG_Numeric, self).__init__(value, name) 104 | if buffer: 105 | self._parse_buffer(buffer) 106 | 107 | #Parsers and Generators 108 | def _parse_buffer(self, buffer): 109 | # Note: buffer.read() may raise an IOError, for example if buffer is a corrupt gzip.GzipFile 110 | self.value = self.fmt.unpack(buffer.read(self.fmt.size))[0] 111 | 112 | def _render_buffer(self, buffer): 113 | buffer.write(self.fmt.pack(self.value)) 114 | 115 | class _TAG_End(TAG): 116 | id = TAG_END 117 | fmt = Struct(">b") 118 | 119 | def _parse_buffer(self, buffer): 120 | # Note: buffer.read() may raise an IOError, for example if buffer is a corrupt gzip.GzipFile 121 | value = self.fmt.unpack(buffer.read(1))[0] 122 | if value != 0: 123 | raise ValueError("A Tag End must be rendered as '0', not as '%d'." % (value)) 124 | 125 | def _render_buffer(self, buffer): 126 | buffer.write(b'\x00') 127 | 128 | #== Value Tags ==# 129 | class TAG_Byte(_TAG_Numeric): 130 | """Represent a single tag storing 1 byte.""" 131 | id = TAG_BYTE 132 | fmt = Struct(">b") 133 | 134 | class TAG_Short(_TAG_Numeric): 135 | """Represent a single tag storing 1 short.""" 136 | id = TAG_SHORT 137 | fmt = Struct(">h") 138 | 139 | class TAG_Int(_TAG_Numeric): 140 | """Represent a single tag storing 1 int.""" 141 | id = TAG_INT 142 | fmt = Struct(">i") 143 | """Struct(">i"), 32-bits integer, big-endian""" 144 | 145 | class TAG_Long(_TAG_Numeric): 146 | """Represent a single tag storing 1 long.""" 147 | id = TAG_LONG 148 | fmt = Struct(">q") 149 | 150 | class TAG_Float(_TAG_Numeric): 151 | """Represent a single tag storing 1 IEEE-754 floating point number.""" 152 | id = TAG_FLOAT 153 | fmt = Struct(">f") 154 | 155 | class TAG_Double(_TAG_Numeric): 156 | """Represent a single tag storing 1 IEEE-754 double precision floating point number.""" 157 | id = TAG_DOUBLE 158 | fmt = Struct(">d") 159 | 160 | class TAG_Byte_Array(TAG, MutableSequence): 161 | """ 162 | TAG_Byte_Array, comparable to a collections.UserList with 163 | an intrinsic name whose values must be bytes 164 | """ 165 | id = TAG_BYTE_ARRAY 166 | def __init__(self, name=None, buffer=None): 167 | # TODO: add a value parameter as well 168 | super(TAG_Byte_Array, self).__init__(name=name) 169 | if buffer: 170 | self._parse_buffer(buffer) 171 | 172 | #Parsers and Generators 173 | def _parse_buffer(self, buffer): 174 | length = TAG_Int(buffer=buffer) 175 | self.value = bytearray(buffer.read(length.value)) 176 | 177 | def _render_buffer(self, buffer): 178 | length = TAG_Int(len(self.value)) 179 | length._render_buffer(buffer) 180 | buffer.write(bytes(self.value)) 181 | 182 | # Mixin methods 183 | def __len__(self): 184 | return len(self.value) 185 | 186 | def __iter__(self): 187 | return iter(self.value) 188 | 189 | def __contains__(self, item): 190 | return item in self.value 191 | 192 | def __getitem__(self, key): 193 | return self.value[key] 194 | 195 | def __setitem__(self, key, value): 196 | # TODO: check type of value 197 | self.value[key] = value 198 | 199 | def __delitem__(self, key): 200 | del(self.value[key]) 201 | 202 | def insert(self, key, value): 203 | # TODO: check type of value, or is this done by self.value already? 204 | self.value.insert(key, value) 205 | 206 | #Printing and Formatting of tree 207 | def valuestr(self): 208 | return "[%i byte(s)]" % len(self.value) 209 | 210 | def __unicode__(self): 211 | return '['+",".join([unicode(x) for x in self.value])+']' 212 | def __str__(self): 213 | return '['+",".join([str(x) for x in self.value])+']' 214 | 215 | class TAG_Int_Array(TAG, MutableSequence): 216 | """ 217 | TAG_Int_Array, comparable to a collections.UserList with 218 | an intrinsic name whose values must be integers 219 | """ 220 | id = TAG_INT_ARRAY 221 | def __init__(self, name=None, buffer=None): 222 | # TODO: add a value parameter as well 223 | super(TAG_Int_Array, self).__init__(name=name) 224 | if buffer: 225 | self._parse_buffer(buffer) 226 | 227 | def update_fmt(self, length): 228 | """ Adjust struct format description to length given """ 229 | self.fmt = Struct(">" + str(length) + "i") 230 | 231 | #Parsers and Generators 232 | def _parse_buffer(self, buffer): 233 | length = TAG_Int(buffer=buffer).value 234 | self.update_fmt(length) 235 | self.value = list(self.fmt.unpack(buffer.read(self.fmt.size))) 236 | 237 | def _render_buffer(self, buffer): 238 | length = len(self.value) 239 | self.update_fmt(length) 240 | TAG_Int(length)._render_buffer(buffer) 241 | buffer.write(self.fmt.pack(*self.value)) 242 | 243 | # Mixin methods 244 | def __len__(self): 245 | return len(self.value) 246 | 247 | def __iter__(self): 248 | return iter(self.value) 249 | 250 | def __contains__(self, item): 251 | return item in self.value 252 | 253 | def __getitem__(self, key): 254 | return self.value[key] 255 | 256 | def __setitem__(self, key, value): 257 | self.value[key] = value 258 | 259 | def __delitem__(self, key): 260 | del(self.value[key]) 261 | 262 | def insert(self, key, value): 263 | self.value.insert(key, value) 264 | 265 | #Printing and Formatting of tree 266 | def valuestr(self): 267 | return "[%i int(s)]" % len(self.value) 268 | 269 | 270 | class TAG_String(TAG, Sequence): 271 | """ 272 | TAG_String, comparable to a collections.UserString with an 273 | intrinsic name 274 | """ 275 | id = TAG_STRING 276 | def __init__(self, value=None, name=None, buffer=None): 277 | super(TAG_String, self).__init__(value, name) 278 | if buffer: 279 | self._parse_buffer(buffer) 280 | 281 | #Parsers and Generators 282 | def _parse_buffer(self, buffer): 283 | length = TAG_Short(buffer=buffer) 284 | read = buffer.read(length.value) 285 | if len(read) != length.value: 286 | raise StructError() 287 | self.value = read.decode("utf-8") 288 | 289 | def _render_buffer(self, buffer): 290 | save_val = self.value.encode("utf-8") 291 | length = TAG_Short(len(save_val)) 292 | length._render_buffer(buffer) 293 | buffer.write(save_val) 294 | 295 | # Mixin methods 296 | def __len__(self): 297 | return len(self.value) 298 | 299 | def __iter__(self): 300 | return iter(self.value) 301 | 302 | def __contains__(self, item): 303 | return item in self.value 304 | 305 | def __getitem__(self, key): 306 | return self.value[key] 307 | 308 | #Printing and Formatting of tree 309 | def __repr__(self): 310 | return self.value 311 | 312 | #== Collection Tags ==# 313 | class TAG_List(TAG, MutableSequence): 314 | """ 315 | TAG_List, comparable to a collections.UserList with an intrinsic name 316 | """ 317 | id = TAG_LIST 318 | def __init__(self, type=None, value=None, name=None, buffer=None): 319 | super(TAG_List, self).__init__(value, name) 320 | if type: 321 | self.tagID = type.id 322 | else: 323 | self.tagID = None 324 | self.tags = [] 325 | if buffer: 326 | self._parse_buffer(buffer) 327 | if self.tagID == None: 328 | raise ValueError("No type specified for list: %s" % (name)) 329 | 330 | #Parsers and Generators 331 | def _parse_buffer(self, buffer): 332 | self.tagID = TAG_Byte(buffer=buffer).value 333 | self.tags = [] 334 | length = TAG_Int(buffer=buffer) 335 | for x in range(length.value): 336 | self.tags.append(TAGLIST[self.tagID](buffer=buffer)) 337 | 338 | def _render_buffer(self, buffer): 339 | TAG_Byte(self.tagID)._render_buffer(buffer) 340 | length = TAG_Int(len(self.tags)) 341 | length._render_buffer(buffer) 342 | for i, tag in enumerate(self.tags): 343 | if tag.id != self.tagID: 344 | raise ValueError("List element %d(%s) has type %d != container type %d" % 345 | (i, tag, tag.id, self.tagID)) 346 | tag._render_buffer(buffer) 347 | 348 | # Mixin methods 349 | def __len__(self): 350 | return len(self.tags) 351 | 352 | def __iter__(self): 353 | return iter(self.tags) 354 | 355 | def __contains__(self, item): 356 | return item in self.tags 357 | 358 | def __getitem__(self, key): 359 | return self.tags[key] 360 | 361 | def __setitem__(self, key, value): 362 | self.tags[key] = value 363 | 364 | def __delitem__(self, key): 365 | del(self.tags[key]) 366 | 367 | def insert(self, key, value): 368 | self.tags.insert(key, value) 369 | 370 | #Printing and Formatting of tree 371 | def __repr__(self): 372 | return "%i entries of type %s" % (len(self.tags), TAGLIST[self.tagID].__name__) 373 | 374 | #Printing and Formatting of tree 375 | def valuestr(self): 376 | return "[%i %s(s)]" % (len(self.tags), TAGLIST[self.tagID].__name__) 377 | def __unicode__(self): 378 | return "["+", ".join([tag.tag_info() for tag in self.tags])+"]" 379 | def __str__(self): 380 | return "["+", ".join([tag.tag_info() for tag in self.tags])+"]" 381 | 382 | def pretty_tree(self, indent=0): 383 | output = [super(TAG_List, self).pretty_tree(indent)] 384 | if len(self.tags): 385 | output.append(("\t"*indent) + "{") 386 | output.extend([tag.pretty_tree(indent + 1) for tag in self.tags]) 387 | output.append(("\t"*indent) + "}") 388 | return '\n'.join(output) 389 | 390 | class TAG_Compound(TAG, MutableMapping): 391 | """ 392 | TAG_Compound, comparable to a collections.OrderedDict with an 393 | intrinsic name 394 | """ 395 | id = TAG_COMPOUND 396 | def __init__(self, buffer=None, name=None): 397 | # TODO: add a value parameter as well 398 | super(TAG_Compound, self).__init__() 399 | self.tags = [] 400 | self.name = "" 401 | if buffer: 402 | self._parse_buffer(buffer) 403 | 404 | #Parsers and Generators 405 | def _parse_buffer(self, buffer): 406 | while True: 407 | type = TAG_Byte(buffer=buffer) 408 | if type.value == TAG_END: 409 | #print("found tag_end") 410 | break 411 | else: 412 | name = TAG_String(buffer=buffer).value 413 | try: 414 | tag = TAGLIST[type.value](buffer=buffer, name=name) 415 | tag.name = name 416 | self.tags.append(tag) 417 | except KeyError: 418 | raise ValueError("Unrecognised tag type") 419 | 420 | def _render_buffer(self, buffer): 421 | for tag in self.tags: 422 | TAG_Byte(tag.id)._render_buffer(buffer) 423 | TAG_String(tag.name)._render_buffer(buffer) 424 | tag._render_buffer(buffer) 425 | buffer.write(b'\x00') #write TAG_END 426 | 427 | # Mixin methods 428 | def __len__(self): 429 | return len(self.tags) 430 | 431 | def __iter__(self): 432 | for key in self.tags: 433 | yield key.name 434 | 435 | def __contains__(self, key): 436 | if isinstance(key, int): 437 | return key <= len(self.tags) 438 | elif isinstance(key, basestring): 439 | for tag in self.tags: 440 | if tag.name == key: 441 | return True 442 | return False 443 | elif isinstance(key, TAG): 444 | return key in self.tags 445 | return False 446 | 447 | def __getitem__(self, key): 448 | if isinstance(key, int): 449 | return self.tags[key] 450 | elif isinstance(key, basestring): 451 | for tag in self.tags: 452 | if tag.name == key: 453 | return tag 454 | else: 455 | raise KeyError("Tag %s does not exist" % key) 456 | else: 457 | raise TypeError("key needs to be either name of tag, or index of tag, not a %s" % type(key).__name__) 458 | 459 | def __setitem__(self, key, value): 460 | assert isinstance(value, TAG), "value must be an nbt.TAG" 461 | if isinstance(key, int): 462 | # Just try it. The proper error will be raised if it doesn't work. 463 | self.tags[key] = value 464 | elif isinstance(key, basestring): 465 | value.name = key 466 | for i, tag in enumerate(self.tags): 467 | if tag.name == key: 468 | self.tags[i] = value 469 | return 470 | self.tags.append(value) 471 | 472 | def __delitem__(self, key): 473 | if isinstance(key, int): 474 | del(self.tags[key]) 475 | elif isinstance(key, basestring): 476 | self.tags.remove(self.__getitem__(key)) 477 | else: 478 | raise ValueError("key needs to be either name of tag, or index of tag") 479 | 480 | def keys(self): 481 | return [tag.name for tag in self.tags] 482 | 483 | def iteritems(self): 484 | for tag in self.tags: 485 | yield (tag.name, tag) 486 | 487 | #Printing and Formatting of tree 488 | def __unicode__(self): 489 | return "{"+", ".join([tag.tag_info() for tag in self.tags])+"}" 490 | def __str__(self): 491 | return "{"+", ".join([tag.tag_info() for tag in self.tags])+"}" 492 | 493 | def valuestr(self): 494 | return '{%i Entries}' % len(self.tags) 495 | 496 | def pretty_tree(self, indent=0): 497 | output = [super(TAG_Compound, self).pretty_tree(indent)] 498 | if len(self.tags): 499 | output.append(("\t"*indent) + "{") 500 | output.extend([tag.pretty_tree(indent + 1) for tag in self.tags]) 501 | output.append(("\t"*indent) + "}") 502 | return '\n'.join(output) 503 | 504 | 505 | TAGLIST = {TAG_END: _TAG_End, TAG_BYTE:TAG_Byte, TAG_SHORT:TAG_Short, TAG_INT:TAG_Int, TAG_LONG:TAG_Long, TAG_FLOAT:TAG_Float, TAG_DOUBLE:TAG_Double, TAG_BYTE_ARRAY:TAG_Byte_Array, TAG_STRING:TAG_String, TAG_LIST:TAG_List, TAG_COMPOUND:TAG_Compound, TAG_INT_ARRAY:TAG_Int_Array} 506 | 507 | class NBTFile(TAG_Compound): 508 | """Represent an NBT file object.""" 509 | def __init__(self, filename=None, buffer=None, fileobj=None): 510 | """ 511 | Create a new NBTFile object. 512 | Specify either a filename, file object or data buffer. 513 | If filename of file object is specified, data should be GZip-compressed. 514 | If a data buffer is specified, it is assumed to be uncompressed. 515 | 516 | If filename is specified, the file is closed after reading and writing. 517 | If file object is specified, the caller is responsible for closing the file. 518 | """ 519 | super(NBTFile, self).__init__() 520 | self.filename = filename 521 | self.type = TAG_Byte(self.id) 522 | closefile = True 523 | #make a file object 524 | if filename: 525 | self.filename = filename 526 | self.file = GzipFile(filename, 'rb') 527 | elif buffer: 528 | if hasattr(buffer, 'name'): 529 | self.filename = buffer.name 530 | self.file = buffer 531 | closefile = False 532 | elif fileobj: 533 | if hasattr(fileobj, 'name'): 534 | self.filename = fileobj.name 535 | self.file = GzipFile(fileobj=fileobj) 536 | else: 537 | self.file = None 538 | closefile = False 539 | #parse the file given initially 540 | if self.file: 541 | self.parse_file() 542 | if closefile: 543 | # Note: GzipFile().close() does NOT close the fileobj, 544 | # So we are still responsible for closing that. 545 | try: 546 | self.file.close() 547 | except (AttributeError, IOError): 548 | pass 549 | self.file = None 550 | 551 | def parse_file(self, filename=None, buffer=None, fileobj=None): 552 | """Completely parse a file, extracting all tags.""" 553 | if filename: 554 | self.file = GzipFile(filename, 'rb') 555 | elif buffer: 556 | if hasattr(buffer, 'name'): 557 | self.filename = buffer.name 558 | self.file = buffer 559 | elif fileobj: 560 | if hasattr(fileobj, 'name'): 561 | self.filename = fileobj.name 562 | self.file = GzipFile(fileobj=fileobj) 563 | if self.file: 564 | try: 565 | type = TAG_Byte(buffer=self.file) 566 | if type.value == self.id: 567 | name = TAG_String(buffer=self.file).value 568 | self._parse_buffer(self.file) 569 | self.name = name 570 | self.file.close() 571 | else: 572 | raise MalformedFileError("First record is not a Compound Tag") 573 | except StructError as e: 574 | raise MalformedFileError("Partial File Parse: file possibly truncated.") 575 | else: 576 | raise ValueError("NBTFile.parse_file(): Need to specify either a filename or a file object") 577 | 578 | def write_file(self, filename=None, buffer=None, fileobj=None): 579 | """Write this NBT file to a file.""" 580 | closefile = True 581 | if buffer: 582 | self.filename = None 583 | self.file = buffer 584 | closefile = False 585 | elif filename: 586 | self.filename = filename 587 | self.file = GzipFile(filename, "wb") 588 | elif fileobj: 589 | self.filename = None 590 | self.file = GzipFile(fileobj=fileobj, mode="wb") 591 | elif self.filename: 592 | self.file = GzipFile(self.filename, "wb") 593 | elif not self.file: 594 | raise ValueError("NBTFile.write_file(): Need to specify either a filename or a file object") 595 | #Render tree to file 596 | TAG_Byte(self.id)._render_buffer(self.file) 597 | TAG_String(self.name)._render_buffer(self.file) 598 | self._render_buffer(self.file) 599 | #make sure the file is complete 600 | try: 601 | self.file.flush() 602 | except (AttributeError, IOError): 603 | pass 604 | if closefile: 605 | try: 606 | self.file.close() 607 | except (AttributeError, IOError): 608 | pass 609 | 610 | def __repr__(self): 611 | """ 612 | Return a string (ascii formated for Python 2, unicode 613 | for Python 3) describing the class, name and id for 614 | debugging purposes. 615 | """ 616 | if self.filename: 617 | return "<%s(%r) with %s(%r) at 0x%x>" % (self.__class__.__name__, self.filename, \ 618 | TAG_Compound.__name__, self.name, id(self)) 619 | else: 620 | return "<%s with %s(%r) at 0x%x>" % (self.__class__.__name__, \ 621 | TAG_Compound.__name__, self.name, id(self)) 622 | 623 | if __name__=="__main__": 624 | print "NBT library" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /pycraft_minetest/main.py: -------------------------------------------------------------------------------- 1 | import time, random, math, os 2 | from . import connection 3 | from . import blocklist as bl 4 | from . util import * 5 | from . event import * 6 | 7 | LIBRARY_VERSION = 0.6 8 | 9 | conn = None 10 | player = None 11 | 12 | 13 | def connect_server(host="localhost", port=4711): 14 | """ This function connect to a server on a specific port and wait until at 15 | least a client is connected. 16 | 17 | Parameters: 18 | 19 | - host (string) ip or domain name of the server 20 | - port (int) port on which the server is waiting for 21 | connection 22 | 23 | Returns: 24 | 25 | A tuple composed of the connection handle and the player id 26 | 27 | Examples: 28 | 29 | > (conn, player) = connect_server() 30 | 31 | connect to localhost:4711 (default server address:port configuration) 32 | 33 | > (conn, player) = connect_server("localhost", 4711) 34 | 35 | Same effect of the pervious example but with explicit parameters 36 | specification 37 | 38 | > (conn, player) = connect_server(port=4712) 39 | 40 | We are connecting on localhost on an alternate port readnumber 41 | 42 | """ 43 | # Wait for connection 44 | wait_for_conn = True 45 | while wait_for_conn: 46 | try: 47 | conn = connection.Connection(host, port) 48 | except: 49 | print("Waiting for connection...") 50 | time.sleep(1) 51 | else: 52 | wait_for_conn = False 53 | 54 | # Find the player 55 | # players = mc.getPlayerEntityIds() 56 | 57 | # Wait for at least one player 58 | 59 | wait_for_player = True 60 | while wait_for_player: 61 | try: 62 | ids = conn.sendReceive("world.getPlayerIds") 63 | except: 64 | print("Waiting for a player to connect...") 65 | time.sleep(1) 66 | else: 67 | wait_for_player = False 68 | 69 | players = list(map(int, ids.split("|"))) 70 | player = players[0] 71 | return (conn, player) 72 | 73 | 74 | conn, player = connect_server() 75 | 76 | # BLOCKS 77 | air = bl.AIR.id 78 | stone = bl.STONE.id 79 | grass = bl.GRASS.id 80 | dirt = bl.DIRT.id 81 | cobblestone = bl.COBBLESTONE.id 82 | wood_planks = bl.WOOD_PLANKS.id 83 | sapling = bl.SAPLING.id 84 | bedrock = bl.BEDROCK.id 85 | water_flowing = bl.WATER_FLOWING.id 86 | water = bl.WATER.id 87 | water_stationary = bl.WATER_STATIONARY.id 88 | lava_flowing = bl.LAVA_FLOWING.id 89 | lava = bl.LAVA.id 90 | lava_stationary = bl.LAVA_STATIONARY.id 91 | sand = bl.SAND.id 92 | gravel = bl.GRAVEL.id 93 | gold_ore = bl.GOLD_ORE.id 94 | iron_ore = bl.IRON_ORE.id 95 | coal_ore = bl.COAL_ORE.id 96 | wood = bl.WOOD.id 97 | leaves = bl.LEAVES.id 98 | glass = bl.GLASS.id 99 | lapis_lazuli_ore = bl.LAPIS_LAZULI_ORE.id 100 | lapis_lazuli = bl.LAPIS_LAZULI_BLOCK.id 101 | sandstone = bl.SANDSTONE.id 102 | bed = bl.BED.id 103 | cobweb = bl.COBWEB.id 104 | grass_tall = bl.GRASS_TALL.id 105 | wool = bl.WOOL.id 106 | flower_yellow = bl.FLOWER_YELLOW.id 107 | flower_cyan = bl.FLOWER_CYAN.id 108 | mushroom_brown = bl.MUSHROOM_BROWN.id 109 | mushroom_red = bl.MUSHROOM_RED.id 110 | gold = bl.GOLD_BLOCK.id 111 | iron = bl.IRON_BLOCK.id 112 | stone_slab_double = bl.STONE_SLAB_DOUBLE.id 113 | stone_slab = bl.STONE_SLAB.id 114 | brick = bl.BRICK_BLOCK.id 115 | tnt = bl.TNT.id 116 | bookshelf = bl.BOOKSHELF.id 117 | moss_stone = bl.MOSS_STONE.id 118 | obsidian = bl.OBSIDIAN.id 119 | torch = bl.TORCH.id 120 | fire = bl.FIRE.id 121 | stairs_wood = bl.STAIRS_WOOD.id 122 | chest = bl.CHEST.id 123 | diamond_ore = bl.DIAMOND_ORE.id 124 | diamond = bl.DIAMOND_BLOCK.id 125 | crafting_table = bl.CRAFTING_TABLE.id 126 | farmland = bl.FARMLAND.id 127 | furnace_inactive = bl.FURNACE_INACTIVE.id 128 | furnace_active = bl.FURNACE_ACTIVE.id 129 | door_wood = bl.DOOR_WOOD.id 130 | ladder = bl.LADDER.id 131 | stairs_cobblestone = bl.STAIRS_COBBLESTONE.id 132 | door_iron = bl.DOOR_IRON.id 133 | redstone_ore = bl.REDSTONE_ORE.id 134 | ice = bl.ICE.id 135 | snow = bl.SNOW_BLOCK.id 136 | cactus = bl.CACTUS.id 137 | clay = bl.CLAY.id 138 | sugar_cane = bl.SUGAR_CANE.id 139 | fence = bl.FENCE.id 140 | glowstone = bl.GLOWSTONE_BLOCK.id 141 | stone_brick = bl.STONE_BRICK.id 142 | glass_pane = bl.GLASS_PANE.id 143 | melon = bl.MELON.id 144 | fence_gate = bl.FENCE_GATE.id 145 | glowing_obsidian = bl.GLOWING_OBSIDIAN.id 146 | nether_reactor_core = bl.NETHER_REACTOR_CORE.id 147 | #monster_spawner = bl.MONSTER_SPAWNER.id 148 | #standing_sign = bl.STANDING_SIGN_BLOCK.id 149 | #rail = bl.RAIL.id 150 | #lever = bl.LEVER.id 151 | #sponge = bl.SPONGE.id 152 | #pumpkin = bl.PUMPKIN.id 153 | #netherrack = bl.NETHERRACK.id 154 | #soul_sand = bl.SOUL_SAND.id 155 | #jack = bl.JACK.id 156 | #stained_glass = bl.STAINED_GLASS.id 157 | #cobblestone_wall = bl.COBBLESTONE_WALL.id 158 | #prismarine = bl.PRISMARINE.id 159 | #sea_lantern = bl.SEA_LANTERN.id 160 | #hay_bale = bl.HAY_BALE.id 161 | #coal = bl.COAL_BLOCK.id 162 | #magma = bl.MAGMA_BLOCK.id 163 | #redstone = bl.REDSTONE_BLOCK.id 164 | #stained_glass_pane = bl.STAINED_GLASS_PANE.id 165 | #slime = bl.SLIME_BLOCK.id 166 | #carpet = bl.CARPET.id 167 | #redstone_torch = bl.REDSTONE_TORCH.id 168 | #piston = bl.PISTON.id 169 | #sticky_piston = bl.STICKY_PISTON.id 170 | #dispenser = bl.DISPENSER.id 171 | #note = bl.NOTE_BLOCK.id 172 | #stone_pressure_plate = bl.STONE_PRESSURE_PLATE.id 173 | #hopper = bl.HOPPER.id 174 | #dropper = bl.DROPPER.id 175 | #activator_rail = bl.ACTIVATOR_RAIL.id 176 | #powered_rail = bl.POWERED_RAIL.id 177 | #detector_rail = bl.DETECTOR_RAIL.id 178 | #beacon = bl.BEACON.id 179 | #emerald = bl.EMERALD_BLOCK.id 180 | #emerald_ore = bl.EMERALD_ORE.id 181 | #quartz = bl.QUARTZ_BLOCK.id 182 | #barrier = bl.BARRIER.id 183 | 184 | 185 | def getblock(name): 186 | return globals()[name] 187 | 188 | 189 | def chat(text): 190 | conn.send("chat.post", text) 191 | 192 | 193 | def where(target=player): 194 | s = conn.sendReceive("entity" + ".getTile", target) 195 | return Vec3(*map(int, s.split(","))) 196 | 197 | 198 | def move(x=0, y=0, z=0, target=player, absolute=False): 199 | s = conn.sendReceive("entity" + ".getTile", target) 200 | pos = Vec3(*map(int, s.split(","))) 201 | if not absolute: 202 | x += pos.x 203 | y += pos.y 204 | z += pos.z 205 | conn.send("entity" + ".setTile", target, intFloor(x, y, z)) 206 | 207 | 208 | def goto(x=0, y=0, z=0, target=player): 209 | # s = conn.sendReceive("entity" + ".getTile", target) 210 | # pos = Vec3(*map(int, s.split(","))) 211 | # if not absolute: 212 | # x += pos.x 213 | # y += pos.y 214 | # z += pos.z 215 | conn.send("entity" + ".setTile", target, intFloor(x, y, z)) 216 | 217 | 218 | def changex(x=0, target=player): 219 | s = conn.sendReceive("entity" + ".getTile", target) 220 | pos = Vec3(*map(int, s.split(","))) 221 | x += pos.x 222 | y = pos.y 223 | z = pos.z 224 | conn.send("entity" + ".setTile", target, intFloor(x, y, z)) 225 | 226 | 227 | def changey(y=0, target=player): 228 | s = conn.sendReceive("entity" + ".getTile", target) 229 | pos = Vec3(*map(int, s.split(","))) 230 | x = pos.x 231 | y += pos.y 232 | z = pos.z 233 | conn.send("entity" + ".setTile", target, intFloor(x, y, z)) 234 | 235 | 236 | def changez(z=0, target=player): 237 | s = conn.sendReceive("entity" + ".getTile", target) 238 | pos = Vec3(*map(int, s.split(","))) 239 | x = pos.x 240 | y = pos.y 241 | z += pos.z 242 | conn.send("entity" + ".setTile", target, intFloor(x, y, z)) 243 | 244 | 245 | def setx(x=0, target=player): 246 | s = conn.sendReceive("entity" + ".getTile", target) 247 | pos = Vec3(*map(int, s.split(","))) 248 | y = pos.y 249 | z = pos.z 250 | conn.send("entity" + ".setTile", target, intFloor(x, y, z)) 251 | 252 | 253 | def sety(y=0, target=player): 254 | s = conn.sendReceive("entity" + ".getTile", target) 255 | pos = Vec3(*map(int, s.split(","))) 256 | x = pos.x 257 | z = pos.z 258 | conn.send("entity" + ".setTile", target, intFloor(x, y, z)) 259 | 260 | 261 | def setz(z=0, target=player): 262 | s = conn.sendReceive("entity" + ".getTile", target) 263 | pos = Vec3(*map(int, s.split(","))) 264 | x = pos.x 265 | y = pos.y 266 | conn.send("entity" + ".setTile", target, intFloor(x, y, z)) 267 | 268 | 269 | def sphere(block, radius=10, x=0, y=0, z=0, absolute=False, hollow=False, target=player): 270 | if block is list: 271 | block_data = block[1] 272 | block = block[0] 273 | else: 274 | block_data = 0 275 | if not absolute: 276 | s = conn.sendReceive("entity" + ".getTile", target) 277 | pos = Vec3(*map(int, s.split(","))) 278 | x += pos.x 279 | y += pos.y 280 | z += pos.z 281 | if not hollow: 282 | for xd in range(radius * -1, radius): 283 | for yd in range(radius * -1, radius): 284 | for zd in range(radius * -1, radius): 285 | if xd ** 2 + yd ** 2 + zd ** 2 < radius ** 2: 286 | conn.send("world.setBlock", intFloor(x + xd, y + yd, z + zd, block, block_data)) 287 | else: 288 | for xd in range(radius * -1, radius): 289 | for yd in range(radius * -1, radius): 290 | for zd in range(radius * -1, radius): 291 | if (xd ** 2 + yd ** 2 + zd ** 2 < radius ** 2) and (xd ** 2 + yd ** 2 + zd ** 2 > (radius ** 2 - (radius * 2))): 292 | conn.send("world.setBlock", intFloor(x + xd, y + yd, z + zd, block, block_data)) 293 | 294 | 295 | def circle(block, 296 | radius=10, 297 | x=0, y=0, z=0, 298 | direction="vertical", 299 | absolute=False, 300 | target=player): 301 | if block is list: 302 | block_data = block[1] 303 | block = block[0] 304 | else: 305 | block_data = 0 306 | if not absolute: 307 | s = conn.sendReceive("entity" + ".getTile", target) 308 | pos = Vec3(*map(int, s.split(","))) 309 | x += pos.x 310 | y += pos.y 311 | z += pos.z 312 | if direction == "vertical": 313 | f = 1 - radius 314 | ddf_x = 1 315 | ddf_y = -2 * radius 316 | xd = 0 317 | yd = radius 318 | conn.send("world.setBlock", intFloor(x, y + radius, z, block, block_data)) 319 | conn.send("world.setBlock", intFloor(x, y - radius, z, block, block_data)) 320 | conn.send("world.setBlock", intFloor(x + radius, y, z, block, block_data)) 321 | conn.send("world.setBlock", intFloor(x - radius, y, z, block, block_data)) 322 | while xd < yd: 323 | if f >= 0: 324 | yd -= 1 325 | ddf_y += 2 326 | f += ddf_y 327 | xd += 1 328 | ddf_x += 2 329 | f += ddf_x 330 | conn.send("world.setBlock", intFloor(x + xd, y + yd, z, block, block_data)) 331 | conn.send("world.setBlock", intFloor(x - xd, y + yd, z, block, block_data)) 332 | conn.send("world.setBlock", intFloor(x + xd, y - yd, z, block, block_data)) 333 | conn.send("world.setBlock", intFloor(x - xd, y - yd, z, block, block_data)) 334 | conn.send("world.setBlock", intFloor(x + yd, y + xd, z, block, block_data)) 335 | conn.send("world.setBlock", intFloor(x - yd, y + xd, z, block, block_data)) 336 | conn.send("world.setBlock", intFloor(x + yd, y - xd, z, block, block_data)) 337 | conn.send("world.setBlock", intFloor(x - yd, y - xd, z, block, block_data)) 338 | elif direction == "horizontal": 339 | f = 1 - radius 340 | ddf_x = 1 341 | ddf_z = -2 * radius 342 | xd = 0 343 | zd = radius 344 | conn.send("world.setBlock", intFloor(x, y, z + radius, block, block_data)) 345 | conn.send("world.setBlock", intFloor(x, y, z - radius, block, block_data)) 346 | conn.send("world.setBlock", intFloor(x + radius, y, z, block, block_data)) 347 | conn.send("world.setBlock", intFloor(x - radius, y, z, block, block_data)) 348 | while xd < zd: 349 | if f >= 0: 350 | zd -= 1 351 | ddf_z += 2 352 | f += ddf_z 353 | xd += 1 354 | ddf_x += 2 355 | f += ddf_x 356 | conn.send("world.setBlock", intFloor(x + xd, y, z + zd, block, block_data)) 357 | conn.send("world.setBlock", intFloor(x - xd, y, z + zd, block, block_data)) 358 | conn.send("world.setBlock", intFloor(x + xd, y, z - zd, block, block_data)) 359 | conn.send("world.setBlock", intFloor(x - xd, y, z - zd, block, block_data)) 360 | conn.send("world.setBlock", intFloor(x + zd, y, z + xd, block, block_data)) 361 | conn.send("world.setBlock", intFloor(x - zd, y, z + xd, block, block_data)) 362 | conn.send("world.setBlock", intFloor(x + zd, y, z - xd, block, block_data)) 363 | conn.send("world.setBlock", intFloor(x - zd, y, z - xd, block, block_data)) 364 | 365 | 366 | def line(block, x1=0, y1=0, z1=0, x2=0, y2=0, z2=0, absolute=False, target=player): 367 | if block is list: 368 | block_data = block[1] 369 | block = block[0] 370 | else: 371 | block_data = 0 372 | if not absolute: 373 | s = conn.sendReceive("entity" + ".getTile", target) 374 | pos = Vec3(*map(int, s.split(","))) 375 | x1 += pos.x 376 | y1 += pos.y 377 | z1 += pos.z 378 | x2 = pos.x + x2 379 | y2 = pos.y + y2 380 | z2 = pos.z + z2 381 | # List for vertices 382 | vertices = [] 383 | # If the 2 points are the same, return single vertice 384 | if x1 == x2 and y1 == y2 and z1 == z2: 385 | vertices.append(Vec3(x1, y1, z1)) 386 | # Else get all points in edge 387 | else: 388 | dx = x2 - x1 389 | dy = y2 - y1 390 | dz = z2 - z1 391 | ax = abs(dx) << 1 392 | ay = abs(dy) << 1 393 | az = abs(dz) << 1 394 | sx = ZSGN(dx) 395 | sy = ZSGN(dy) 396 | sz = ZSGN(dz) 397 | x = x1 398 | y = y1 399 | z = z1 400 | # X dominant 401 | if ax >= MAX(ay, az): 402 | yd = ay - (ax >> 1) 403 | zd = az - (ax >> 1) 404 | loop = True 405 | while loop: 406 | vertices.append(Vec3(x, y, z)) 407 | if x == x2: 408 | loop = False 409 | if yd >= 0: 410 | y += sy 411 | yd -= ax 412 | if zd >= 0: 413 | z += sz 414 | zd -= ax 415 | x += sx 416 | yd += ay 417 | zd += az 418 | # Y dominant 419 | elif ay >= MAX(ax, az): 420 | xd = ax - (ay >> 1) 421 | zd = az - (ay >> 1) 422 | loop = True 423 | while loop: 424 | vertices.append(Vec3(x, y, z)) 425 | if y == y2: 426 | loop = False 427 | if xd >= 0: 428 | x += sx 429 | xd -= ay 430 | if zd >= 0: 431 | z += sz 432 | zd -= ay 433 | y += sy 434 | xd += ax 435 | zd += az 436 | # Z dominant 437 | elif az >= MAX(ax, ay): 438 | xd = ax - (az >> 1) 439 | yd = ay - (az >> 1) 440 | loop = True 441 | while loop: 442 | vertices.append(Vec3(x, y, z)) 443 | if z == z2: 444 | loop = False 445 | if xd >= 0: 446 | x += sx 447 | xd -= az 448 | if yd >= 0: 449 | y += sy 450 | yd -= az 451 | z += sz 452 | xd += ax 453 | yd += ay 454 | for vertex in vertices: 455 | conn.send("world.setBlock", intFloor(vertex.x, 456 | vertex.y, 457 | vertex.z, 458 | block, 459 | block_data)) 460 | 461 | 462 | def block(block, x=0, y=0, z=0, absolute=False, target=player): 463 | if block is list: 464 | block_data = block[1] 465 | block = block[0] 466 | else: 467 | block_data = 0 468 | if not absolute: 469 | s = conn.sendReceive("entity" + ".getTile", target) 470 | pos = Vec3(*map(int, s.split(","))) 471 | x += pos.x 472 | y += pos.y 473 | z += pos.z 474 | conn.send("world.setBlock", intFloor(x, y, z, block, block_data)) 475 | 476 | 477 | def blocks(block, x1=0, y1=0, z1=0, x=0, y=0, z=0, absolute=False, target=player): 478 | if block is list: 479 | block_data = block[1] 480 | block = block[0] 481 | else: 482 | block_data = 0 483 | if not absolute: 484 | s = conn.sendReceive("entity" + ".getTile", target) 485 | pos = Vec3(*map(int, s.split(","))) 486 | x1 += pos.x 487 | y1 += pos.y 488 | z1 += pos.z 489 | x = pos.x + x 490 | y = pos.y + y 491 | z = pos.z + z 492 | conn.send("world.setBlocks", intFloor(x1, y1, z1, x, y, z, block, block_data)) 493 | 494 | 495 | def cube(block, side=10, x=0, y=0, z=0, absolute=False, target=player): 496 | if block is list: 497 | block_data = block[1] 498 | block = block[0] 499 | else: 500 | block_data = 0 501 | if not absolute: 502 | s = conn.sendReceive("entity" + ".getTile", target) 503 | pos = Vec3(*map(int, s.split(","))) 504 | x += pos.x 505 | y += pos.y 506 | z += pos.z 507 | conn.send("world.setBlocks", intFloor(x, y, z, x + side - 1, y + side - 1, z + side - 1, block, block_data)) 508 | 509 | 510 | def pyramid(block, width=11, x=0, y=0, z=0, absolute=False, target=player): 511 | if block is list: 512 | block_data = block[1] 513 | block = block[0] 514 | else: 515 | block_data = 0 516 | if not absolute: 517 | s = conn.sendReceive("entity" + ".getTile", target) 518 | pos = Vec3(*map(int, s.split(","))) 519 | x += pos.x 520 | y += pos.y 521 | z += pos.z 522 | if width % 2 == 0: 523 | width += 1 524 | if width == 1: 525 | conn.send("world.setBlock", intFloor(x, y, z, block, block_data)) 526 | else: 527 | conn.send("world.setBlocks", intFloor(x, y, z, x + width - 1, y, z + width - 1, block, block_data)) 528 | pyramid(block, width - 2, x + 1, y + 1, z + 1, absolute=True) 529 | 530 | 531 | def over(block, target=player): 532 | s = conn.sendReceive("entity" + ".getTile", target) 533 | pos = Vec3(*map(int, s.split(","))) 534 | material = int(conn.sendReceive("world.getBlock", intFloor(pos.x, pos.y - 1, pos.z))) 535 | if material == block: 536 | return True 537 | else: 538 | return False 539 | 540 | 541 | def under(target=player): 542 | s = conn.sendReceive("entity" + ".getTile", target) 543 | pos = Vec3(*map(int, s.split(","))) 544 | material = int(conn.sendReceive("world.getBlock", intFloor(pos.x, pos.y - 1, pos.z))) 545 | return material 546 | 547 | 548 | def what(x, y, z, absolute=False, target=player): 549 | if not absolute: 550 | s = conn.sendReceive("entity" + ".getTile", target) 551 | pos = Vec3(*map(int, s.split(","))) 552 | x += pos.x 553 | y += pos.y 554 | z += pos.z 555 | material = int(conn.sendReceive("world.getBlock", intFloor(x, y, z))) 556 | return material 557 | 558 | 559 | def near(block, radius=10, target=player): 560 | s = conn.sendReceive("entity" + ".getTile", target) 561 | pos = Vec3(*map(int, s.split(","))) 562 | blocks = conn.sendReceive("world.getBlocks", intFloor(pos.x - radius, 563 | pos.y - radius, 564 | pos.z - radius, 565 | pos.x + radius, 566 | pos.y + radius, 567 | pos.z + radius)) 568 | blocks = map(int, blocks.split(",")) 569 | for b in blocks: 570 | if b == block: 571 | return True 572 | return False 573 | 574 | 575 | def readnumber(text=""): 576 | done = False 577 | value = 0 578 | while not done: 579 | try: 580 | value = int(input_from_chat(text)) 581 | done = True 582 | except: 583 | chat("Il valore inserito non e' un numero valido") 584 | return value 585 | 586 | 587 | def readstring(text=""): 588 | done = False 589 | value = 0 590 | while not done: 591 | try: 592 | value = input_from_chat(text) 593 | done = True 594 | except: 595 | chat("Il valore inserito non e' valido") 596 | return value 597 | 598 | 599 | def input_from_chat(text): 600 | chat(text) 601 | read_done = False 602 | value = "0" 603 | while not read_done: 604 | s = conn.sendReceive("events.chat.posts") 605 | events = [e for e in s.split("|") if e] 606 | poll = [ChatEvent.Post(int(e[:e.find(",")]), e[e.find(",") + 1:]) for e in events] 607 | for msg in poll: 608 | value = msg.message 609 | read_done = True 610 | break 611 | time.sleep(0.10) 612 | return value 613 | 614 | 615 | def polygon(block, shape=6, side=10, x=0, y=0, z=0, direction="horizontal", absolute=False, target=player): 616 | if direction == "horizontal": 617 | if block is list: 618 | block_data = block[1] 619 | block = block[0] 620 | else: 621 | block_data = 0 622 | if not absolute: 623 | s = conn.sendReceive("entity" + ".getTile", target) 624 | pos = Vec3(*map(int, s.split(","))) 625 | x = x + pos.x 626 | y = y + pos.y 627 | z = z + pos.z 628 | angle = 0 629 | i = shape 630 | side -= 1 631 | startx = x 632 | startz = z 633 | while i > 0: 634 | if i == 1: 635 | targetx = startx 636 | targetz = startz 637 | else: 638 | targetx = int(round(x + side * math.cos(angle), 0)) 639 | targetz = int(round(z + side * math.sin(angle), 0)) 640 | # Line starts here: 641 | # List for vertices 642 | vertices = [] 643 | # If the 2 points are the same, return single vertice 644 | if x == targetx and y == y and z == targetz: 645 | vertices.append(Vec3(x, y, z)) 646 | # Else get all points in edge 647 | else: 648 | dx = targetx - x 649 | dy = y - y 650 | dz = targetz - z 651 | ax = abs(dx) << 1 652 | ay = abs(dy) << 1 653 | az = abs(dz) << 1 654 | sx = ZSGN(dx) 655 | sy = ZSGN(dy) 656 | sz = ZSGN(dz) 657 | x = x 658 | y = y 659 | z = z 660 | # X dominant 661 | if ax >= MAX(ay, az): 662 | yd = ay - (ax >> 1) 663 | zd = az - (ax >> 1) 664 | loop = True 665 | while loop: 666 | vertices.append(Vec3(x, y, z)) 667 | if x == targetx: 668 | loop = False 669 | if yd >= 0: 670 | y += sy 671 | yd -= ax 672 | if zd >= 0: 673 | z += sz 674 | zd -= ax 675 | x += sx 676 | yd += ay 677 | zd += az 678 | # Y dominant 679 | elif ay >= MAX(ax, az): 680 | xd = ax - (ay >> 1) 681 | zd = az - (ay >> 1) 682 | loop = True 683 | while loop: 684 | vertices.append(Vec3(x, y, z)) 685 | if y == y: 686 | loop = False 687 | if xd >= 0: 688 | x += sx 689 | xd -= ay 690 | if zd >= 0: 691 | z += sz 692 | zd -= ay 693 | y += sy 694 | xd += ax 695 | zd += az 696 | # Z dominant 697 | elif az >= MAX(ax, ay): 698 | xd = ax - (az >> 1) 699 | yd = ay - (az >> 1) 700 | loop = True 701 | while loop: 702 | vertices.append(Vec3(x, y, z)) 703 | if z == targetz: 704 | loop = False 705 | if xd >= 0: 706 | x += sx 707 | xd -= az 708 | if yd >= 0: 709 | y += sy 710 | yd -= az 711 | z += sz 712 | xd += ax 713 | yd += ay 714 | for vertex in vertices: 715 | conn.send("world.setBlock", intFloor(vertex.x, 716 | vertex.y, 717 | vertex.z, 718 | block, 719 | block_data)) 720 | # line(block, x, y, z, targetx, y, targetz) 721 | angle += 2 * math.pi / shape 722 | x = targetx 723 | z = targetz 724 | i -= 1 725 | 726 | 727 | def turtle(penblock, target=player): 728 | chat('Remember that class names should be Capital Letter (Turtle, not turtle)!') 729 | return Turtle(penblock, target) 730 | 731 | 732 | def maze(csvpath, base=grass, wall=gold, obstacle=lava, target=player): 733 | # open maze csv 734 | f = open(csvpath, "r") 735 | # find player position 736 | s = conn.sendReceive("entity" + ".getTile", target) 737 | pos = Vec3(*map(int, s.split(","))) 738 | # define z start coordinate 739 | z = pos.z+1 740 | # for each line of the csv... 741 | for line in f.readlines(): 742 | data = line.split(",") 743 | # restart from the original x at every loop cycle 744 | x = pos.x+1 745 | # for each cell in the list... 746 | for cell in data: 747 | if cell == "0": 748 | selectedblock = air 749 | elif cell == "2": 750 | selectedblock = obstacle 751 | else: 752 | selectedblock = wall 753 | # set the selected block 754 | conn.send("world.setBlock", intFloor(x, pos.y, z, selectedblock)) 755 | conn.send("world.setBlock", intFloor(x, pos.y+1, z, selectedblock)) 756 | # build the floor 757 | conn.send("world.setBlock", intFloor(x, pos.y-1, z, base)) 758 | # move on the x axis 759 | x = x + 1 760 | # move on the z axis 761 | z = z + 1 762 | 763 | 764 | #class chatListener: 765 | # 766 | # 767 | #def __init__(self): 768 | #self.start() 769 | # 770 | #def start(self) : 771 | #self.run = True 772 | #self.thread = threading.Thread(target=self.listen) 773 | #self.thread.start() 774 | # 775 | #def listen(self) : 776 | #while self.run: 777 | #for msg in mc.events.pollChatPosts(): 778 | #mc.postToChat(msg.message) 779 | #time.sleep(0.10) 780 | # 781 | #def exit(self) : 782 | #self.run = False 783 | # 784 | #chatl = chatListener() 785 | 786 | 787 | # TURTLE CLASS 788 | class Turtle: 789 | 790 | SPEEDTIMES = {0: 0, 791 | 12: 0.001, 792 | 11: 0.01, 793 | 10: 0.1, 794 | 9: 0.2, 795 | 8: 0.3, 796 | 7: 0.4, 797 | 6: 0.5, 798 | 5: 0.6, 799 | 4: 0.7, 800 | 3: 0.8, 801 | 2: 0.9, 802 | 1: 1} 803 | 804 | def __init__(self, penblock, target=player): 805 | # Player 806 | self.player = player 807 | # Start position 808 | s = conn.sendReceive("entity" + ".getTile", target) 809 | self.startposition = Vec3(*map(int, s.split(","))) 810 | # Set turtle position 811 | self.position = Vec3(*map(int, s.split(","))) 812 | # Set turtle angles 813 | self.heading = 0 814 | self.verticalheading = 0 815 | # Set pen down 816 | self._pendown = True 817 | # Set pen bl to black wool 818 | self._penblock = bl.Block(bl.WOOL.id, 15) 819 | # Flying to true 820 | self.flying = True 821 | # Set speed 822 | self.turtlespeed = 6 823 | # Create turtle 824 | self.showturtle = True 825 | # Set turtle block 826 | self.turtleblock = bl.Block(bl.DIAMOND_BLOCK.id) 827 | # Draw turtle 828 | self.draw_turtle(int(self.position.x), int(self.position.y), int(self.position.y)) 829 | # Previous vertical heading 830 | self.previous = 0 831 | # Last turtle 832 | self.last_drawn_turtle = Vec3(0, 0, 0) 833 | # Pen block 834 | self.penblock(penblock) 835 | # Speed 836 | self.speed(10) 837 | 838 | def forward(self, distance): 839 | # Get end of line 840 | x, y, z = self.find_point_on_sphere(self.position.x, 841 | self.position.y, 842 | self.position.z, 843 | self.heading, 844 | self.verticalheading, 845 | distance) 846 | # Move turtle forward 847 | self.move_turtle(x, y, z) 848 | 849 | def backward(self, distance): 850 | # Get end of line 851 | x, y, z = self.find_point_on_sphere(self.position.x, 852 | self.position.y, 853 | self.position.z, 854 | self.heading, 855 | self.verticalheading - 180, 856 | distance) 857 | # Move turtle forward 858 | self.move_turtle(x, y, z) 859 | 860 | def move_turtle(self, x, y, z): 861 | # Get blocks between current position and next 862 | target_x, target_y, target_z = int(x), int(y), int(z) 863 | # If walking, set target Y to be height of world 864 | if self.flying is False: 865 | target_y = int(conn.sendReceive(target_x, target_z)) 866 | current_x, current_y, current_z = int(self.position.x), int(self.position.y), int(self.position.z) 867 | # Clear the turtle 868 | if self.showturtle: 869 | self.clear_turtle(self.last_drawn_turtle.x, self.last_drawn_turtle.y, self.last_drawn_turtle.z) 870 | # If speed is 0 and flying, just draw the line, else animate it 871 | if self.turtlespeed == 0 and self.flying: 872 | # Draw the line 873 | if self._pendown: 874 | line(self._penblock.id, current_x, current_y - 1, current_z, target_x, target_y - 1, target_z) 875 | else: 876 | blocks_between = getLine(current_x, current_y, current_z, target_x, target_y, target_z) 877 | if 215 < self.verticalheading < 315: 878 | self.previous = -1 879 | for block_between in blocks_between: 880 | # If walking update the y, to be the height of the world 881 | if self.flying is False: 882 | block_between.y = int(conn.sendReceive(block_between.x, block_between.z)) 883 | # Draw the turtle 884 | if self.showturtle: 885 | self.draw_turtle(block_between.x, block_between.y - 2, block_between.z) 886 | # Draw the pen 887 | if self._pendown: 888 | conn.send("world.setBlock", intFloor(block_between.x, 889 | block_between.y - 1, 890 | block_between.z, 891 | self._penblock.id, 892 | self._penblock.data)) 893 | # Wait 894 | time.sleep(self.SPEEDTIMES[self.turtlespeed]) 895 | # Clear the turtle 896 | if self.showturtle: 897 | self.clear_turtle(block_between.x, block_between.y - 2, block_between.z) 898 | # Update turtle's position to be the target 899 | self.position.x, self.position.y, self.position.z = x, y, z 900 | # Draw turtle 901 | if self.showturtle: 902 | self.draw_turtle(target_x, target_y - 2, target_z) 903 | elif 45 < self.verticalheading < 135: 904 | self.previous = 1 905 | for block_between in blocks_between: 906 | # If walking update the y, to be the height of the world 907 | if self.flying is False: 908 | block_between.y = int(conn.sendReceive(block_between.x, block_between.z)) 909 | # Draw the turtle 910 | if self.showturtle: 911 | self.draw_turtle(block_between.x, block_between.y, block_between.z) 912 | # Draw the pen 913 | if self._pendown: 914 | conn.send("world.setBlock", intFloor(block_between.x, 915 | block_between.y - 1, 916 | block_between.z, 917 | self._penblock.id, 918 | self._penblock.data)) 919 | # Wait 920 | time.sleep(self.SPEEDTIMES[self.turtlespeed]) 921 | # Clear the turtle 922 | if self.showturtle: 923 | self.clear_turtle(block_between.x, block_between.y, block_between.z) 924 | # Update turtle's position to be the target 925 | self.position.x, self.position.y, self.position.z = x, y, z 926 | # Draw turtle 927 | if self.showturtle: 928 | self.draw_turtle(target_x, target_y, target_z) 929 | else: 930 | if self.previous == -1: 931 | for block_between in blocks_between: 932 | # If walking update the y, to be the height of the world 933 | if self.flying is False: 934 | block_between.y = int(conn.sendReceive(block_between.x, block_between.z)) 935 | # Draw the turtle 936 | if self.showturtle: 937 | self.draw_turtle(block_between.x, block_between.y - 2, block_between.z) 938 | if self._pendown: 939 | conn.send("world.setBlock", intFloor(block_between.x, 940 | block_between.y - 1, 941 | block_between.z, 942 | self._penblock.id, 943 | self._penblock.data)) 944 | time.sleep(self.SPEEDTIMES[self.turtlespeed]) 945 | if self.showturtle: 946 | self.clear_turtle(block_between.x, block_between.y - 2, block_between.z) 947 | # Update turtle's position to be the target 948 | self.position.x, self.position.y, self.position.z = x, y, z 949 | # Draw turtle 950 | if self.showturtle: 951 | self.draw_turtle(target_x, target_y - 2, target_z) 952 | else: 953 | for block_between in blocks_between: 954 | # If walking update the y, to be the height of the world 955 | if self.flying is False: 956 | block_between.y = int(conn.sendReceive(block_between.x, block_between.z)) 957 | # Draw the turtle 958 | if self.showturtle: 959 | self.draw_turtle(block_between.x, block_between.y, block_between.z) 960 | if self._pendown: 961 | conn.send("world.setBlock", intFloor(block_between.x, 962 | block_between.y - 1, 963 | block_between.z, 964 | self._penblock.id, 965 | self._penblock.data)) 966 | time.sleep(self.SPEEDTIMES[self.turtlespeed]) 967 | if self.showturtle: 968 | self.clear_turtle(block_between.x, block_between.y, block_between.z) 969 | # Update turtle's position to be the target 970 | self.position.x, self.position.y, self.position.z = x, y, z 971 | # Draw turtle 972 | if self.showturtle: 973 | self.draw_turtle(target_x, target_y, target_z) 974 | self.previous = 0 975 | 976 | def right(self, angle): 977 | # Rotate turtle angle to the right 978 | self.heading = self.heading + angle 979 | if self.heading > 360: 980 | self.heading = self.heading - 360 981 | 982 | def left(self, angle): 983 | # Rotate turtle angle to the left 984 | self.heading = self.heading - angle 985 | if self.heading < 0: 986 | self.heading = self.heading + 360 987 | 988 | def up(self, angle): 989 | # Rotate turtle angle up 990 | self.verticalheading = self.verticalheading + angle 991 | if self.verticalheading > 360: 992 | self.verticalheading = self.verticalheading - 360 993 | # Turn flying on 994 | if self.flying is False: 995 | self.flying = True 996 | 997 | def down(self, angle): 998 | # Rotate turtle angle down 999 | self.verticalheading = self.verticalheading - angle 1000 | if self.verticalheading < 0: 1001 | self.verticalheading = self.verticalheading + 360 1002 | # Turn flying on 1003 | if self.flying is False: 1004 | self.flying = True 1005 | 1006 | def goto(self, x=0, y=0, z=0, absolute=True): 1007 | if not absolute: 1008 | pos = where(player) 1009 | # Clear the turtle 1010 | if self.showturtle: 1011 | self.clear_turtle(self.position.x, 1012 | self.position.y, 1013 | self.position.z) 1014 | # Update the position 1015 | self.position.x = pos.x + x 1016 | self.position.y = pos.y + y 1017 | self.position.z = pos.z + z 1018 | # Draw the turtle 1019 | if self.showturtle: 1020 | self.draw_turtle(self.position.x, 1021 | self.position.y, 1022 | self.position.z) 1023 | else: 1024 | # Clear the turtle 1025 | if self.showturtle: 1026 | self.clear_turtle(self.position.x, 1027 | self.position.y, 1028 | self.position.z) 1029 | # Update the position 1030 | self.position.x = x 1031 | self.position.y = y 1032 | self.position.z = z 1033 | # Draw the turtle 1034 | if self.showturtle: 1035 | self.draw_turtle(self.position.x, 1036 | self.position.y, 1037 | self.position.z) 1038 | 1039 | def setposition(self, x=0, y=0, z=0, absolute=False): 1040 | self.goto(x, y, z, absolute) 1041 | 1042 | def move(self, x=0, y=0, z=0, absolute=False): 1043 | self.goto(x, y, z, absolute) 1044 | 1045 | def setx(self, x): 1046 | self.goto(x, self.position.y, self.position.z) 1047 | 1048 | def sety(self, y): 1049 | self.goto(self.position.x, y, self.position.z) 1050 | 1051 | def setz(self, z): 1052 | self.goto(self.position.x, self.position.y, z) 1053 | 1054 | def changex(self, x): 1055 | self.move(x, 0, 0) 1056 | 1057 | def changey(self, y): 1058 | self.move(0, y, 0) 1059 | 1060 | def changez(self, z): 1061 | self.move(0, 0, z) 1062 | 1063 | def setheading(self, angle): 1064 | self.heading = angle 1065 | 1066 | def setverticalheading(self, angle): 1067 | self.verticalheading = angle 1068 | # Turn flying on 1069 | if self.flying is False: 1070 | self.flying = True 1071 | 1072 | def gohome(self): 1073 | self.goto(self.startposition.x, 1074 | self.startposition.y, 1075 | self.startposition.z) 1076 | 1077 | def pendown(self): 1078 | self._pendown = True 1079 | 1080 | def penup(self): 1081 | self._pendown = False 1082 | 1083 | def isdown(self): 1084 | return self.pendown 1085 | 1086 | def fly(self): 1087 | self.flying = True 1088 | 1089 | def walk(self): 1090 | self.flying = False 1091 | self.verticalheading = 0 1092 | 1093 | def penblock(self, blockId, blockData=0): 1094 | self._penblock = bl.Block(blockId, blockData) 1095 | 1096 | def speed(self, turtlespeed): 1097 | self.turtlespeed = turtlespeed 1098 | 1099 | def draw_turtle(self, x, y, z): 1100 | # Draw turtle 1101 | conn.send("world.setBlock", intFloor(x, y, z, self.turtleblock.id, self.turtleblock.data)) 1102 | self.last_drawn_turtle = Vec3(x, y, z) 1103 | 1104 | def clear_turtle(self, x, y, z): 1105 | # Clear turtle 1106 | conn.send("world.setBlock", intFloor(x, y, z, bl.AIR.id)) 1107 | 1108 | def find_target_block(self, turtle_x, turtle_y, turtle_z, heading, verticalheading, distance): 1109 | x, y, z = self.find_point_on_sphere(turtle_x, turtle_y, turtle_z, heading, verticalheading, distance) 1110 | x = int(round(x, 0)) 1111 | y = int(round(y, 0)) 1112 | z = int(round(z, 0)) 1113 | return x, y, z 1114 | 1115 | def find_point_on_sphere(self, cx, cy, cz, horizontal_angle, vertical_angle, radius): 1116 | x = cx + (radius * (math.cos(math.radians(vertical_angle)) * math.cos(math.radians(horizontal_angle)))) 1117 | y = cy + (radius * (math.sin(math.radians(vertical_angle)))) 1118 | z = cz + (radius * (math.cos(math.radians(vertical_angle)) * math.sin(math.radians(horizontal_angle)))) 1119 | return x, y, z 1120 | 1121 | def round_xyz(self, x, y, z): 1122 | return int(round(x, 0)), int(round(y, 0)), int(round(z, 0)) 1123 | 1124 | def round_vec3(self, position): 1125 | return Vec3(int(position.x), int(position.y), int(position.z)) 1126 | 1127 | --------------------------------------------------------------------------------