...
 
Commits (5)
import pycraft_minetest as pcmt
import pycraft_minetest.blocklist as blocklist
class PycraftMaterialsLibrary():
matlibrary = {}
def __init__(self):
self.matlibrary = self.buildDictWithBlockNamesValues()
def getBlockName(self, id):
l = self.matlibrary.values()
if id in l:
i = l.index(id)
return self.matlibrary.keys()[i]
else:
return "what is the name of block number {}?".format(id)
def getBlockId(self, name):
if name in self.matlibrary:
return self.matlibrary[name]
else:
return pcmt.gold # default block if name is unknown
def testNameInPcmt(self, name, id):
for r in dir(pcmt):
try:
pcmtid = getattr(pcmt, r)
if (pcmtid == id) and ((r == name) or (r+'_BLOCK'.lower() == name)): # _block removed from name
return r
except:
pass
return None
def buildDictWithBlockNamesValues(self):
blockNames = dir(blocklist) # get all variables in blocklist.py
blockDict = {}
bn = None
for bn in blockNames:
try:
val = getattr(blocklist, bn) # try to get the value of the symbol
if isinstance(val, blocklist.Block):
bnpcmt = bn.lower()
bnpcmt_renamed = self.testNameInPcmt(bnpcmt, val.id)
if bnpcmt_renamed is not None:
blockDict[bnpcmt_renamed] = val.id
#print(bnpcmt,val.id)
#bv = pcmt.getblock(bn.lower())
#w[bn] = bv
except:
pass
return blockDict
if __name__ == "__main__":
w = PycraftMaterialsLibrary()
print (w.matlibrary)
print(w.getBlockName(w.matlibrary['fire']))
print(w.getBlockName(89))
minetest-mod-pycraft (0.22-1) unstable; urgency=medium
* New upstream version 0.22.
- Removed 1000-busted-test.patch and 1010-python3.patch now
applied upstream.
* Adjusted d/watch to use new upstream release tags.
-- Petter Reinholdtsen <pere@debian.org> Sun, 20 Jan 2019 12:44:03 +0100
minetest-mod-pycraft (0.20+git20180331.0376a0a+dfsg-3) unstable; urgency=medium
* Added missing build/binary dependency lua-bitop.
......
Description: Add simple unit test for lua module.
Author: Petter Reinholdtsen <pere@debian.org>
are templates for supplementary fields that you might want to add:
Origin: <vendor|upstream|other>, <url of original patch>
Bug: <url in upstream bugtracker>
Bug-Debian: https://bugs.debian.org/<bugnumber>
Bug-Ubuntu: https://launchpad.net/bugs/<bugnumber>
Forwarded: <no|not-needed|url proving that it has been forwarded>
Reviewed-By: <name and email of someone who approved the patch>
Last-Update: 2018-12-02
--- /dev/null
+++ minetest-mod-pycraft-0.20+git20180331.0376a0a/tests/pycraft_spec.lua
@@ -0,0 +1,73 @@
+-- unit tests using busted
+-- based on https://rubenwardy.com/minetest_modding_book/en/quality/unit_testing.html
+
+-- Look for required things in
+package.path = "../?.lua;" .. package.path
+
+_G.minetest = {}
+minetest.registered_nodes = {}
+
+-- Define the mock functions
+function minetest.get_current_modname()
+ return "something"
+end
+function minetest.get_modpath()
+ return "some/path"
+end
+function minetest.register_globalstep(f)
+ minetest.globalstep = f
+end
+function minetest.register_on_shutdown(f)
+end
+function minetest.register_on_joinplayer(f)
+end
+function minetest.register_on_leaveplayer(f)
+end
+function minetest.register_on_punchnode(f)
+end
+function minetest.register_chatcommand(f)
+end
+function minetest.register_on_chat_message(f)
+end
+
+_G.Settings = {}
+Settings.__index = Settings
+setmetatable(Settings, {
+ __call = function (cls, ...)
+ return cls.new(...)
+ end,
+})
+function Settings.get(self,field)
+ print("get", field)
+ return self.vars[field]
+end
+function Settings:get_bool(field)
+ print("get_bool", field)
+ return self.vars[field]
+end
+function Settings:set(field, value)
+ print("set", field, value)
+ self.vars[field] = value
+ return
+end
+function Settings.new(filepath)
+ local self = setmetatable({}, MyClass)
+ self.filepath = filepath
+ self.vars = {}
+ self.vars["python"] = "python"
+ self.vars["restrict_to_local_connections"] = true
+ self.vars["support_websockets"] = true
+ self.get=Settings.get
+ self.get_bool=Settings.get_bool
+ self.set=Settings.set
+ return self
+end
+
+mod = require("init")
+
+describe("simple", function()
+ it("test", function()
+ minetest.globalstep(1)
+-- assert.equals(0, some-call)
+ end)
+end)
Description: Port library code to python 3
Author: Petter Reinholdtsen <pere@debian.org>
Origin: https://github.com/sprintingkiwi/pycraft_mod/pull/1
Forwarded: https://github.com/sprintingkiwi/pycraft_mod/pull/1
Reviewed-By: Petter Reinholdtsen <pere@debian.org>
Last-Update: 2018-12-02
--- minetest-mod-pycraft-0.20+git20180331.0376a0a.orig/mcpipy/mcpi/block.py
+++ minetest-mod-pycraft-0.20+git20180331.0376a0a/mcpipy/mcpi/block.py
@@ -1,4 +1,4 @@
-import settings
+from . import settings
class Block:
"""Minecraft PI block description. Can be sent to Minecraft.setBlock/s"""
--- minetest-mod-pycraft-0.20+git20180331.0376a0a.orig/mcpipy/mcpi/connection.py
+++ minetest-mod-pycraft-0.20+git20180331.0376a0a/mcpipy/mcpi/connection.py
@@ -7,7 +7,7 @@ import os
import platform
import base64
from hashlib import md5
-from util import flatten_parameters_to_string
+from .util import flatten_parameters_to_string
""" @author: Aron Nieminen, Mojang AB"""
--- minetest-mod-pycraft-0.20+git20180331.0376a0a.orig/mcpipy/mcpi/event.py
+++ minetest-mod-pycraft-0.20+git20180331.0376a0a/mcpipy/mcpi/event.py
@@ -1,4 +1,4 @@
-from vec3 import Vec3
+from .vec3 import Vec3
class BlockEvent:
"""An Event related to blocks (e.g. placed, removed, hit)"""
--- minetest-mod-pycraft-0.20+git20180331.0376a0a.orig/mcpipy/mcpi/minecraft.py
+++ minetest-mod-pycraft-0.20+git20180331.0376a0a/mcpipy/mcpi/minecraft.py
@@ -1,11 +1,11 @@
-from connection import Connection,RequestError
-from vec3 import Vec3
-from event import BlockEvent,ChatEvent
-from block import Block
+from .connection import Connection,RequestError
+from .vec3 import Vec3
+from .event import BlockEvent,ChatEvent
+from .block import Block
import math
from os import environ
-from util import flatten,floorFlatten
-import security
+from .util import flatten,floorFlatten
+from . import security
""" Minecraft PI low level api v0.1_1
@@ -62,12 +62,12 @@ class CmdPositioner:
def getDirection(self, id):
"""Get entity direction (entityId:int) => Vec3"""
s = self.conn.sendReceive(self.pkg + ".getDirection", id)
- return Vec3(*map(float, s.split(",")))
+ return Vec3(*list(map(float, s.split(","))))
def getPos(self, id):
"""Get entity position (entityId:int) => Vec3"""
s = self.conn.sendReceive(self.pkg + ".getPos", id)
- return Vec3(*map(float, s.split(",")))
+ return Vec3(*list(map(float, s.split(","))))
def setPos(self, id, *args):
"""Set entity position (entityId:int, x,y,z)"""
@@ -88,7 +88,7 @@ class CmdPositioner:
def getTilePos(self, id, *args):
"""Get entity tile position (entityId:int) => Vec3"""
s = self.conn.sendReceive(self.pkg + ".getTile", id)
- return Vec3(*map(int, s.split(",")))
+ return Vec3(*list(map(int, s.split(","))))
def setTilePos(self, id, *args):
"""Set entity tile position (entityId:int) => Vec3"""
@@ -169,7 +169,7 @@ class CmdEvents:
"""Only triggered by sword => [BlockEvent]"""
s = self.conn.sendReceive("events.block.hits")
events = [e for e in s.split("|") if e]
- return [BlockEvent.Hit(*map(int, e.split(","))) for e in events]
+ return [BlockEvent.Hit(*list(map(int, e.split(",")))) for e in events]
def pollChatPosts(self):
"""Triggered by posts to chat => [ChatEvent]"""
@@ -233,7 +233,7 @@ class Minecraft:
def getBlockWithData(self, *args):
"""Get block with data (x,y,z) => Block"""
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
- return Block(*map(int, ans.split(",")[:2]))
+ return Block(*list(map(int, ans.split(",")[:2])))
def getBlockWithNBT(self, *args):
"""
@@ -256,7 +256,7 @@ class Minecraft:
"""
def fallbackGetCuboid(self, getBlock, *args):
- (x0,y0,z0,x1,y1,z1) = map(lambda x:int(math.floor(float(x))), flatten(args))
+ (x0,y0,z0,x1,y1,z1) = [int(math.floor(float(x))) for x in flatten(args)]
out = []
for y in range(min(y0,y1),max(y0,y1)+1):
for x in range(min(x0,x1),max(x0,x1)+1):
@@ -280,7 +280,7 @@ class Minecraft:
"""
try:
ans = self.conn.sendReceive_flat("world.getBlocks", floorFlatten(args))
- return map(int, ans.split(","))
+ return list(map(int, ans.split(",")))
except:
self.getBlocks = self.fallbackGetBlocks
return self.fallbackGetBlocks(*args)
@@ -289,7 +289,7 @@ class Minecraft:
"""Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [Block(id:int, meta:int)]"""
try:
ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args))
- return [Block(*map(int, x.split(",")[:2])) for x in ans.split("|")]
+ return [Block(*list(map(int, x.split(",")[:2]))) for x in ans.split("|")]
except:
self.getBlocksWithData = self.fallbackGetBlocksWithData
return self.fallbackGetBlocksWithData(*args)
@@ -348,7 +348,7 @@ class Minecraft:
def getPlayerEntityIds(self):
"""Get the entity ids of the connected players => [id:int]"""
ids = self.conn.sendReceive("world.getPlayerIds")
- return map(int, ids.split("|"))
+ return list(map(int, ids.split("|")))
def saveCheckpoint(self):
"""Save a checkpoint that can be used for restoring the world"""
--- minetest-mod-pycraft-0.20+git20180331.0376a0a.orig/mcpipy/mcpi/nbt.py
+++ minetest-mod-pycraft-0.20+git20180331.0376a0a/mcpipy/mcpi/nbt.py
@@ -29,11 +29,11 @@ from collections import MutableMapping,
import os, io
try:
- unicode
- basestring
+ str
+ str
except NameError:
- unicode = str # compatibility for Python 3
- basestring = str # compatibility for Python 3
+ str = str # compatibility for Python 3
+ str = str # compatibility for Python 3
TAG_END = 0
@@ -76,7 +76,7 @@ class TAG(object):
": " + self.valuestr()
def valuestr(self):
"""Return Unicode string of unnested value. For iterators, this returns a summary."""
- return unicode(self.value)
+ return str(self.value)
def pretty_tree(self, indent=0):
"""Return formated Unicode string of self, where iterable items are recursively listed in detail."""
@@ -85,7 +85,7 @@ class TAG(object):
# Python 2 compatibility; Python 3 uses __str__ instead.
def __unicode__(self):
"""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."""
- return unicode(self.value)
+ return str(self.value)
def __str__(self):
"""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."""
@@ -208,7 +208,7 @@ class TAG_Byte_Array(TAG, MutableSequenc
return "[%i byte(s)]" % len(self.value)
def __unicode__(self):
- return '['+",".join([unicode(x) for x in self.value])+']'
+ return '['+",".join([str(x) for x in self.value])+']'
def __str__(self):
return '['+",".join([str(x) for x in self.value])+']'
@@ -435,7 +435,7 @@ class TAG_Compound(TAG, MutableMapping):
def __contains__(self, key):
if isinstance(key, int):
return key <= len(self.tags)
- elif isinstance(key, basestring):
+ elif isinstance(key, str):
for tag in self.tags:
if tag.name == key:
return True
@@ -447,7 +447,7 @@ class TAG_Compound(TAG, MutableMapping):
def __getitem__(self, key):
if isinstance(key, int):
return self.tags[key]
- elif isinstance(key, basestring):
+ elif isinstance(key, str):
for tag in self.tags:
if tag.name == key:
return tag
@@ -461,7 +461,7 @@ class TAG_Compound(TAG, MutableMapping):
if isinstance(key, int):
# Just try it. The proper error will be raised if it doesn't work.
self.tags[key] = value
- elif isinstance(key, basestring):
+ elif isinstance(key, str):
value.name = key
for i, tag in enumerate(self.tags):
if tag.name == key:
@@ -472,7 +472,7 @@ class TAG_Compound(TAG, MutableMapping):
def __delitem__(self, key):
if isinstance(key, int):
del(self.tags[key])
- elif isinstance(key, basestring):
+ elif isinstance(key, str):
self.tags.remove(self.__getitem__(key))
else:
raise ValueError("key needs to be either name of tag, or index of tag")
@@ -621,4 +621,4 @@ class NBTFile(TAG_Compound):
TAG_Compound.__name__, self.name, id(self))
if __name__=="__main__":
- print "NBT library"
\ No newline at end of file
+ print("NBT library")
--- minetest-mod-pycraft-0.20+git20180331.0376a0a.orig/mcpipy/mcpi/util.py
+++ minetest-mod-pycraft-0.20+git20180331.0376a0a/mcpipy/mcpi/util.py
@@ -3,7 +3,7 @@ import math
def flatten(l):
for e in l:
- if isinstance(e, collections.Iterable) and not isinstance(e, basestring):
+ if isinstance(e, collections.Iterable) and not isinstance(e, str):
for ee in flatten(e): yield ee
else: yield e
1000-busted-test.patch
1010-python3.patch
1020-mod-description.patch
version=4
opts="repack, mode=git, gitmode=full, pgpmode=none" \
https://github.com/sprintingkiwi/pycraft_mod/ HEAD
version=3
opts=\
filenamemangle=s/.*\/v?([\d\.-]+)\.tar\.gz/minetest-mod-pycraft-$1.tar.gz/ \
https://github.com/sprintingkiwi/pycraft_mod/releases \
.*/archive/v?([\d\.]+).tar.gz
import pycraft_minetest as pcmt
import pycraft_minetest.blocklist as blocklist
import PIL as pl
"""
converte immagini jpg/png/gif in minetest usando blocchi di lana colorata come pixel
crea immagine in verticale a posizione assoluta
"""
# https://stackoverflow.com/questions/1109422/getting-list-of-pixel-values-from-pil
from PIL import Image
def distance(woolrgb, cpixel):
""" ricerca il blocco di lana colorata piu' vicino al colore del pixel """
r = cpixel[0]
g = cpixel[1]
b = cpixel[2]
did = 0
dmin = 255*255*3
for i in woolrgb:
dr = r - woolrgb[i][0]
dg = g - woolrgb[i][1]
db = b - woolrgb[i][2]
d = dr*dr+dg*dg+db*db
if d < dmin:
dmin = d
did = i
return did
def imageToMinecraftColor(fname):
im = Image.open(fname)
print(im.size)
#gray = im.convert('1')
#bw = gray.point(lambda x: 0 if x < 128 else 255, '1')
bw = im
pixels = bw.load() # this is not a list, nor is it list()'able
width, height = bw.size
bw.show()
woolrgb, woolnames = minecraftrgbColors()
for x in range(width):
print (x)
for y in range(height):
cpixel = pixels[x, y]
xc = x
yc = (height-y)+8
zc = 0
matId = distance(woolrgb, cpixel)
#if matId==0:
# mat=pcmt.air
#else:
mat = woolnames[matId]
pcmt.block(mat, x=xc, y=yc, z=zc, absolute=True)
def imageToMinecraftBW(fname):
im = Image.open(fname)
print(im.size)
gray = im.convert('1') # L opzione punteggiata
bw = gray.point(lambda x: 0 if x < 128 else 255, '1')
pixels = bw.load() # this is not a list, nor is it list()'able
width, height = bw.size
bw.show()
for x in range(width):
print (x)
for y in range(height):
cpixel = pixels[x, y]
xc = x
yc = (height-y)+10
zc = 0
if cpixel > 0:
mat = pcmt.glowstone
else:
mat = pcmt.ice
pcmt.block(mat, x=xc, y=yc, z=zc, absolute=True)
def minecraftrgbColors():
"""
codici colori dei blocchi wool
https://minecraft.gamepedia.com/Wool
"""
wool={ 0: '#E9ECEC',
1: '#F07613',
2: '#BD44B3',
3: '#3AAFD9',
4: '#F8C627',
5: '#70B919',
6: '#ED8DAC',
7: '#3E4447',
8: '#8E8E86',
9: '#158991',
10: '#792AAC',
11: '#35399D',
12: '#724728',
13: '#546D1B',
14: '#A12722',
15: '#141519'}
woolrgb={}
w = ['WOOL_WHITE',
'WOOL_ORANGE',
'WOOL_MAGENTA',
'WOOL_LIGHT_BLUE',
'WOOL_YELLOW',
'WOOL_LIME',
'WOOL_PINK',
'WOOL_GRAY',
'WOOL_LIGHT_GRAY',
'WOOL_CYAN',
'WOOL_PURPLE',
'WOOL_BLUE',
'WOOL_BROWN',
'WOOL_GREEN',
'WOOL_RED',
'WOOL_BLACK']
i = 0
woolnames={}
for id in wool:
col = wool[id]
r = int('0x'+col[1:3], 0)
g = int('0x'+col[3:5], 0)
b = int('0x'+col[5:7], 0)
woolrgb[id] = [r, g, b]
woolblock = getattr(blocklist, w[i])
woolnames[id] = woolblock
i = i + 1
return woolrgb, woolnames
def colors():
col=['WOOL_WHITE',
'WOOL_ORANGE',
'WOOL_MAGENTA',
'WOOL_LIGHT_BLUE',
'WOOL_YELLOW',
'WOOL_LIME',
'WOOL_PINK',
'WOOL_GRAY',
'WOOL_LIGHT_GRAY',
'WOOL_CYAN',
'WOOL_PURPLE',
'WOOL_BLUE',
'WOOL_BROWN',
'WOOL_GREEN',
'WOOL_RED',
'WOOL_BLACK']
for i in range(0,len(col)):
c = getattr(blocklist,col[i])
pcmt.block(c, i, 0, 0)
#colors()
imageToMinecraftColor("c:\\temp\\scratch.png")
#minecraftrgbColors()
\ No newline at end of file
......@@ -864,4 +864,4 @@ end
-- io.popen("python scratch_pycraft.py")
-- os.execute("python scratch_pycraft.py")
import settings
from . import settings
class Block:
"""Minecraft PI block description. Can be sent to Minecraft.setBlock/s"""
......
......@@ -7,7 +7,7 @@ import os
import platform
import base64
from hashlib import md5
from util import flatten_parameters_to_string
from .util import flatten_parameters_to_string
""" @author: Aron Nieminen, Mojang AB"""
......
from vec3 import Vec3
from .vec3 import Vec3
class BlockEvent:
"""An Event related to blocks (e.g. placed, removed, hit)"""
......
from connection import Connection,RequestError
from vec3 import Vec3
from event import BlockEvent,ChatEvent
from block import Block
from .connection import Connection,RequestError
from .vec3 import Vec3
from .event import BlockEvent,ChatEvent
from .block import Block
import math
from os import environ
from util import flatten,floorFlatten
import security
from .util import flatten,floorFlatten
from . import security
""" Minecraft PI low level api v0.1_1
......@@ -62,12 +62,12 @@ class CmdPositioner:
def getDirection(self, id):
"""Get entity direction (entityId:int) => Vec3"""
s = self.conn.sendReceive(self.pkg + ".getDirection", id)
return Vec3(*map(float, s.split(",")))
return Vec3(*list(map(float, s.split(","))))
def getPos(self, id):
"""Get entity position (entityId:int) => Vec3"""
s = self.conn.sendReceive(self.pkg + ".getPos", id)
return Vec3(*map(float, s.split(",")))
return Vec3(*list(map(float, s.split(","))))
def setPos(self, id, *args):
"""Set entity position (entityId:int, x,y,z)"""
......@@ -88,7 +88,7 @@ class CmdPositioner:
def getTilePos(self, id, *args):
"""Get entity tile position (entityId:int) => Vec3"""
s = self.conn.sendReceive(self.pkg + ".getTile", id)
return Vec3(*map(int, s.split(",")))
return Vec3(*list(map(int, s.split(","))))
def setTilePos(self, id, *args):
"""Set entity tile position (entityId:int) => Vec3"""
......@@ -169,7 +169,7 @@ class CmdEvents:
"""Only triggered by sword => [BlockEvent]"""
s = self.conn.sendReceive("events.block.hits")
events = [e for e in s.split("|") if e]
return [BlockEvent.Hit(*map(int, e.split(","))) for e in events]
return [BlockEvent.Hit(*list(map(int, e.split(",")))) for e in events]
def pollChatPosts(self):
"""Triggered by posts to chat => [ChatEvent]"""
......@@ -233,7 +233,7 @@ class Minecraft:
def getBlockWithData(self, *args):
"""Get block with data (x,y,z) => Block"""
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
return Block(*map(int, ans.split(",")[:2]))
return Block(*list(map(int, ans.split(",")[:2])))
def getBlockWithNBT(self, *args):
"""
......@@ -256,7 +256,7 @@ class Minecraft:
"""
def fallbackGetCuboid(self, getBlock, *args):
(x0,y0,z0,x1,y1,z1) = map(lambda x:int(math.floor(float(x))), flatten(args))
(x0,y0,z0,x1,y1,z1) = [int(math.floor(float(x))) for x in flatten(args)]
out = []
for y in range(min(y0,y1),max(y0,y1)+1):
for x in range(min(x0,x1),max(x0,x1)+1):
......@@ -280,7 +280,7 @@ class Minecraft:
"""
try:
ans = self.conn.sendReceive_flat("world.getBlocks", floorFlatten(args))
return map(int, ans.split(","))
return list(map(int, ans.split(",")))
except:
self.getBlocks = self.fallbackGetBlocks
return self.fallbackGetBlocks(*args)
......@@ -289,7 +289,7 @@ class Minecraft:
"""Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [Block(id:int, meta:int)]"""
try:
ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args))
return [Block(*map(int, x.split(",")[:2])) for x in ans.split("|")]
return [Block(*list(map(int, x.split(",")[:2]))) for x in ans.split("|")]
except:
self.getBlocksWithData = self.fallbackGetBlocksWithData
return self.fallbackGetBlocksWithData(*args)
......@@ -348,7 +348,7 @@ class Minecraft:
def getPlayerEntityIds(self):
"""Get the entity ids of the connected players => [id:int]"""
ids = self.conn.sendReceive("world.getPlayerIds")
return map(int, ids.split("|"))
return list(map(int, ids.split("|")))
def saveCheckpoint(self):
"""Save a checkpoint that can be used for restoring the world"""
......
......@@ -29,11 +29,11 @@ from collections import MutableMapping, MutableSequence, Sequence
import os, io
try:
unicode
basestring
str
str
except NameError:
unicode = str # compatibility for Python 3
basestring = str # compatibility for Python 3
str = str # compatibility for Python 3
str = str # compatibility for Python 3
TAG_END = 0
......@@ -76,7 +76,7 @@ class TAG(object):
": " + self.valuestr()
def valuestr(self):
"""Return Unicode string of unnested value. For iterators, this returns a summary."""
return unicode(self.value)
return str(self.value)
def pretty_tree(self, indent=0):
"""Return formated Unicode string of self, where iterable items are recursively listed in detail."""
......@@ -85,7 +85,7 @@ class TAG(object):
# Python 2 compatibility; Python 3 uses __str__ instead.
def __unicode__(self):
"""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."""
return unicode(self.value)
return str(self.value)
def __str__(self):
"""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."""
......@@ -208,7 +208,7 @@ class TAG_Byte_Array(TAG, MutableSequence):
return "[%i byte(s)]" % len(self.value)
def __unicode__(self):
return '['+",".join([unicode(x) for x in self.value])+']'
return '['+",".join([str(x) for x in self.value])+']'
def __str__(self):
return '['+",".join([str(x) for x in self.value])+']'
......@@ -435,7 +435,7 @@ class TAG_Compound(TAG, MutableMapping):
def __contains__(self, key):
if isinstance(key, int):
return key <= len(self.tags)
elif isinstance(key, basestring):
elif isinstance(key, str):
for tag in self.tags:
if tag.name == key:
return True
......@@ -447,7 +447,7 @@ class TAG_Compound(TAG, MutableMapping):
def __getitem__(self, key):
if isinstance(key, int):
return self.tags[key]
elif isinstance(key, basestring):
elif isinstance(key, str):
for tag in self.tags:
if tag.name == key:
return tag
......@@ -461,7 +461,7 @@ class TAG_Compound(TAG, MutableMapping):
if isinstance(key, int):
# Just try it. The proper error will be raised if it doesn't work.
self.tags[key] = value
elif isinstance(key, basestring):
elif isinstance(key, str):
value.name = key
for i, tag in enumerate(self.tags):
if tag.name == key:
......@@ -472,7 +472,7 @@ class TAG_Compound(TAG, MutableMapping):
def __delitem__(self, key):
if isinstance(key, int):
del(self.tags[key])
elif isinstance(key, basestring):
elif isinstance(key, str):
self.tags.remove(self.__getitem__(key))
else:
raise ValueError("key needs to be either name of tag, or index of tag")
......@@ -621,4 +621,4 @@ class NBTFile(TAG_Compound):
TAG_Compound.__name__, self.name, id(self))
if __name__=="__main__":
print "NBT library"
\ No newline at end of file
print("NBT library")
......@@ -3,7 +3,7 @@ import math
def flatten(l):
for e in l:
if isinstance(e, collections.Iterable) and not isinstance(e, basestring):
if isinstance(e, collections.Iterable) and not isinstance(e, str):
for ee in flatten(e): yield ee
else: yield e
......
io.popen("python scratch_pycraft.py")
os.execute("python scratch_pycraft.py")
{
{
"extensionName": "Scratch_Pycraft",
"extensionPort": 3316,
"blockSpecs": [
[" ", "sphere block %s radius %n x %n y %n z %n", "sphere"],
[" ", "cube block %s side %n x %n y %n z %n", "cube"]
[" ", "cube block %s side %n x %n y %n z %n", "cube"],
["b", "over block %s", "over"]
]
}
{
"extensionName": "Scratch_Turtle Pycraft",
"extensionPort": 3320,
"blockSpecs": [
[" ", "reset turtle", "reset_turtle"],
["w", "move %n steps", "forward", 1],
["w", "turn left %n degrees", "left", 90],
["w", "turn right %n degrees", "right", 90],
["w", "turn up %n degrees", "up", 90],
["w", "turn down %n degrees", "down", 90],
["w", "go to x %n y %n z %n", "goto"],
["w", "point in direction %n", "pointto", 90],
["w", "pen up", "penup"],
["w", "pen down", "pendown"],
["w", "set pen block to %s", "penblock"],
["r", "what", "what"],
["h", "when distance %s %n", "whenDistance", "<", 20],
["r", "position x", "posx"],
["r", "position y", "posy"],
["r", "position z", "posz"]
],
"menus": {
"blocktype":["glowstone", "wool", "wood", "ice", "gold"]
}
}
#! /usr/bin/python
# Scratch Hue Helper app
# ----------------------
# (c) 2015 Chris Proctor
# Distributed under the MIT license.
# Project homepage: http://mrproctor.net/scratch
# Scratch Helper app
# ------------------
# template based on work of Chris Proctor, Project homepage: http://mrproctor.net/scratch
#
# main document
# https://wiki.scratch.mit.edu/w/images/ExtensionsDoc.HTTP-9-11.pdf
# Scratch Extension Protocol Discussion
# https://scratch.mit.edu/discuss/topic/18117/
#
import json
import requests
......@@ -23,8 +27,6 @@ import warnings
warnings.filterwarnings("ignore")
app = Flask("Scratch_Pycraft")
app.logger.removeHandler(app.logger.handlers[0])
......@@ -38,7 +40,8 @@ for logger in loggers:
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# jobs keeps the waiting jobs id. blocks type:'w'
# TODO implement a system to return value to scratch (blocks type: 'r')
jobs = set()
@app.route('/poll')
......@@ -75,10 +78,14 @@ def cube(block, side, x, y, z):
return "OK"
@app.route('/over/<string:block>')
def over(block):
#print("check if player is over " + block)
return pcmt.over(pcmt.getblock(block))
print(" * The Scratch helper app for controlling Hue lights is running. Have fun :)")
print(" * The Scratch helper app is running. Have fun :)")
print(" * See mrproctor.net/scratch for help.")
print(" * Press Control + C to quit.")
......
#! /usr/bin/python
# Scratch Helper app
# ------------------
# template based on work of Chris Proctor, Project homepage: http://mrproctor.net/scratch
# https://github.com/cproctor/scratch_hue
#
# main document
# https://wiki.scratch.mit.edu/w/images/ExtensionsDoc.HTTP-9-11.pdf
# Scratch Extension Protocol Discussion
# https://wiki.scratch.mit.edu/wiki/Scratch_Extension
# https://scratch.mit.edu/discuss/topic/18117/
# scratchx extension
# https://github.com/LLK/scratchx/wiki
# hat blocks
# https://scratch.mit.edu/discuss/topic/49736/
# wedo extension
# https://scratch.mit.edu/scratchr2/static/js/scratch_extensions/wedoExtension.js
# framework scratch/snap
# https://github.com/blockext/blockext/tree/master/blockext
# flask objects
# http://flask.pocoo.org/docs/0.12/api/
#
# install Flask (conda install flask)
# pip install pycraft-minetest
#
# TODO blocco over non funziona, provare con true invece di True
# TODO blocco per leggere la chat e inserire le risposte in say
# TODO blocco hat vedere cone funziona
#
# TODO [" ", "point in direction %n", "pointto", 90],
# TODO [" ", "set pen to block type %m.blocktype", "penblock", "ice"],
# TODO mettere i colori delsetblock come menu wool e poi un setblock libero con nome materiale
#
from flask import Flask, request
import logging
import pycraft_minetest as pcmt
import time
from PycraftMaterialsLibrary import PycraftMaterialsLibrary
"""
global variables
"""
app = Flask("Scratch_Pycraft")
EXTENSION_PORT = 3320
myturtle = None
jobs = set() # jobs keeps the waiting jobs id. blocks type:'w'
variables = {} # addVariable to return values to scratch (blocks type: 'r')
materialLibray = PycraftMaterialsLibrary()
def initLogger(app):
""" initialize logger, app to DEBUG and flask to ERROR """
from sys import stdout
app.logger.removeHandler(app.logger.handlers[0])
loggers = [[app.logger, logging.DEBUG, logging.StreamHandler(stdout)],
[logging.getLogger('werkzeug'), logging.ERROR, logging.NullHandler()]]
# handler = logging.FileHandler('"Scratch_Pycraft".log')
formatter = logging.Formatter('%(asctime)s - %(name)14s - %(levelname)s - %(message)s')
for logger in loggers:
handler = logger[2]
handler.setFormatter(formatter)
logger[0].addHandler(handler)
logger[0].setLevel(logger[1])
@app.errorhandler(Exception)
def exceptions(e):
app.logger.debug(e)
@app.before_request
def after_request():
if request.path != "/poll": # to avoid not necessary logs
app.logger.debug("received {}".format(request.full_path))
# scratch protocol path
@app.route('/poll')
def poll():
global myturtle, jobs, variables
where() # update position
s = "\n".join(["_busy {}".format(job) for job in jobs])
s = s + "\n".join(["{} {}".format(var, variables[var]) for var in variables.keys()])
#b = s
#if b.strip() != "":
# print(b)
return s
@app.route('/reset_all')
def reset_all():
global myturtle, jobs, variables
jobs = set()
variables = {}
return "OK"
@app.route('/crossdomain.xml')
def cross_domain_check():
return '<cross-domain-policy><allow-access-from domain="*" to-ports="'+EXTENSION_PORT+'"/></cross-domain-policy>'
# PYCRAFT FUNCTIONS:
def log(s):
app.logger.debug("executing {}".format(s))
pcmt.chat("turtle received: {}".format(s))
def addVariable(varName, varValue):
global myturtle, jobs, variables
variables[varName] = str(varValue)
@app.route('/reset_turtle')
def reset_turtle():
global myturtle, jobs, variables
myturtle = initTurtle()
return "OK"
def where():
"""
called from poll to update position and block under feet
warning: poll calls us 30 times for second
if it slow down everything, we should cache the position and update 1 or 2 times every second
"""
global myturtle, jobs, variables
pos = pcmt.where()
und = pcmt.under() #pcmt.what(0, -1, 0, absolute=False)
undName = materialLibray.getBlockName(und)
addVariable("posx", pos.x)
addVariable("posy", pos.y)
addVariable("posz", pos.z)
addVariable("what", undName)
return "OK"
@app.route('/penup/<int:jobId>')
def penup(jobId):
global myturtle, jobs, variables
jobs.add(jobId)
log("penup")
myturtle.penup()
jobs.remove(jobId)
return "OK"
@app.route('/pendown/<int:jobId>')
def pendown(jobId):
global myturtle, jobs, variables
jobs.add(jobId)
log("pendown")
myturtle.pendown()
jobs.remove(jobId)
return "OK"
@app.route('/up/<int:jobId>/<int:angle>')
def up(jobId,angle):
global myturtle, jobs, variables
jobs.add(jobId)
log("up {}".format(angle))
myturtle.up(angle)
jobs.remove(jobId)
return "OK"
@app.route('/down/<int:jobId>/<int:angle>')
def down(jobId, angle):
global myturtle, jobs, variables
jobs.add(jobId)
log("down {}".format(angle))
myturtle.down(angle)
jobs.remove(jobId)
return "OK"
@app.route('/forward/<int:jobId>/<int:steps>')
def forward(jobId, steps):
global myturtle, jobs, variables
jobs.add(jobId)
log("forward {}".format(steps))
myturtle.forward(steps)
jobs.remove(jobId)
return "OK"
@app.route('/left/<int:jobId>/<int:degrees>')
def left(jobId, degrees):
global myturtle, jobs, variables
jobs.add(jobId)
log("left {}".format(degrees))
myturtle.left(degrees)
jobs.remove(jobId)
return "OK"
@app.route('/right/<int:jobId>/<int:degrees>')
def right(jobId, degrees):
global myturtle, jobs, variables
jobs.add(jobId)
log("right {}".format(degrees))
myturtle.right(degrees)
jobs.remove(jobId)
return "OK"
@app.route('/goto/<int:jobId>/<int:x>/<int:y>/<int:z>')
def goto(jobId, x, y, z):
global myturtle, jobs, variables
jobs.add(jobId)
log("goto x {} y {} z {}".format(x, y, z))
myturtle.goto(x, y, z)
jobs.remove(jobId)
return "OK"
@app.route('/penblock/<int:jobId>/<string:block>')
def penblock(jobId, block):
global myturtle, jobs, variables
jobs.add(jobId)
id = materialLibray.getBlockId(block)
log("penblock {}[{}]".format(block, id))
myturtle.penblock(id)
jobs.remove(jobId)
return "OK"
"""
@app.route('/cube/<int:jobId>/<string:block>/<int:side>/<int:x>/<int:y>/<int:z>')
def cube(jobId, block, side, x, y, z):
global myturtle, jobs, variables
jobs.add(jobId)
print(block, side, x, y, z)
pcmt.cube(pcmt.getblock(block), side, x, y, z)
jobs.remove(jobId)
return "OK"
"""
def initTurtle():
t = pcmt.Turtle(pcmt.glowstone)
t.clear_turtle(0, 0, 0)
t.setheading(0)
t.setverticalheading(0)
t.setposition(0, 0, 0)
t.speed(12) # create a block for speed?
pcmt.chat("turtle created")
app.logger.debug("turtle created {}".format(str(t)))
return t
def main():
global app, myturtle, EXTENSION_PORT
initLogger(app)
print(" **************************************************")
print(" * The Scratch helper app is running. Have fun :) *")
print(" * *")
print(" *** creating turtle *** *")
print(" * Press Control + C to quit. *")
print(" **************************************************")
myturtle = initTurtle()
done = False
while not done:
try:
app.run('0.0.0.0', port=EXTENSION_PORT)
except:
print("trying again")
time.sleep(1)
else:
print("scratch_pyturtlecraft done")
done = True
if __name__ == "__main__":
main()
-- unit tests using busted
-- based on https://rubenwardy.com/minetest_modding_book/en/quality/unit_testing.html
-- Look for required things in
package.path = "../?.lua;" .. package.path
_G.minetest = {}
minetest.registered_nodes = {}
-- Define the mock functions
function minetest.get_current_modname()
return "something"
end
function minetest.get_modpath()
return "some/path"
end
function minetest.register_globalstep(f)
minetest.globalstep = f
end
function minetest.register_on_shutdown(f)
end
function minetest.register_on_joinplayer(f)
end
function minetest.register_on_leaveplayer(f)
end
function minetest.register_on_punchnode(f)
end
function minetest.register_chatcommand(f)
end
function minetest.register_on_chat_message(f)
end
_G.Settings = {}
Settings.__index = Settings
setmetatable(Settings, {
__call = function (cls, ...)
return cls.new(...)
end,
})
function Settings.get(self,field)
print("get", field)
return self.vars[field]
end
function Settings:get_bool(field)
print("get_bool", field)
return self.vars[field]
end
function Settings:set(field, value)
print("set", field, value)
self.vars[field] = value
return
end
function Settings.new(filepath)
local self = setmetatable({}, MyClass)
self.filepath = filepath
self.vars = {}
self.vars["python"] = "python"
self.vars["restrict_to_local_connections"] = true
self.vars["support_websockets"] = true
self.get=Settings.get
self.get_bool=Settings.get_bool
self.set=Settings.set
return self
end
mod = require("init")
describe("simple", function()
it("test", function()
minetest.globalstep(1)
-- assert.equals(0, some-call)
end)
end)