Commit 6acceba7 authored by Petter Reinholdtsen's avatar Petter Reinholdtsen

Update upstream source from tag 'upstream/0.22'

Update to upstream version '0.22'
with Debian dir 7c475ebdfa9cb3dbe01064d6ba1d0368df0f2699
parents a7942784 2b302d69
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))
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)