forked from jbaragry/mcpi-scratch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcpi-scratch.py
334 lines (306 loc) · 13.2 KB
/
mcpi-scratch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# simple httpserver to act as a Scratch2 helper app
# adapted from : http://pymotw.com/2/BaseHTTPServer/
# add python minecraft examples from http://www.stuffaboutcode.com/
import sys, traceback
import argparse, urllib
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
import mcpi.minecraft as minecraft
import mcpi.block as block
import logging
import time
MCPI_CONNECT_TIMEOUT=5
logging.basicConfig(level=logging.DEBUG)
#logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
class GetHandler(BaseHTTPRequestHandler):
def setBlock(self, params):
print ('setblock: {0}'.format(params))
x = int(params[0])
y = int(params[1])
z = int(params[2])
blockType = int(params[3])
blockData = int(params[4])
if (params[5] == 'rel'): # set the block relative to the player
playerPos = mc.player.getTilePos()
#playerPos = minecraft.Vec3(int(playerPos.x), int(playerPos.y), int(playerPos.z))
x += playerPos.x
y += playerPos.y
z += playerPos.z
if (blockData == -1): # sure these is a more pythonesque way of doing this
mc.setBlock(x, y, z, blockType)
else:
mc.setBlock(x, y, z, blockType, blockData)
return ''
def setBlocks(self, params): # doesn't support metadata
log.info('invoke setBlocks with params: {} {} {} {} {} {} {} {}'.format(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7]))
if (int(params[7]) == -1): # sure these is a more pythonesque way of doing this
log.debug('invoking without data')
mc.setBlocks(int(params[0]), int(params[1]), int(params[2]), int(params[3]), int(params[4]), int(params[5]), int(params[6]))
else:
log.debug('invoking with data')
mc.setBlocks(int(params[0]), int(params[1]), int(params[2]), int(params[3]), int(params[4]), int(params[5]), int(params[6]), int(params[7]))
return ''
def setPlayerPos(self, params): # doesn't support metadata
log.info('invoke setPlayerPos with params: {} {} {}'.format(params[0], params[1], params[2]))
mc.player.setPos(int(params[0]), int(params[1]), int(params[2]))
return ''
# implementation of Bresenham's Line Algorithm to rasterise the points in a line between two endpoints
# algorithm taken from: http://www.roguebasin.com/index.php?title=Bresenham%27s_Line_Algorithm#Python
# note: y refers to usual cartesian x,y coords. Not the minecraft coords where y is the veritical axis
def getLinePoints(self, x1, y1, x2, y2):
points = []
issteep = abs(y2-y1) > abs(x2-x1)
if issteep:
x1, y1 = y1, x1
x2, y2 = y2, x2
rev = False
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
rev = True
deltax = x2 - x1
deltay = abs(y2-y1)
error = int(deltax / 2)
y = y1
ystep = None
if y1 < y2:
ystep = 1
else:
ystep = -1
for x in range(x1, x2 + 1):
if issteep:
points.append((y, x))
else:
points.append((x, y))
error -= deltay
if error < 0:
y += ystep
error += deltax
# Reverse the list if the coordinates were reversed
if rev:
points.reverse()
return points
# calls getLine to rasterise a line between two points, the last param is the vertical axis.
# eg: x1,z1,x2,z2,y in minecraft coordinates
# then plots the line using setBlock
def setLine(self, params):
log.info('invoke setLine with params: {} {} {} {} {}'.format(params[0], params[1], params[2], params[3], params[4], params[5]))
log.debug(params)
x1 = int(params[0])
z1 = int(params[1])
x2 = int(params[2])
z2 = int(params[3])
y = int(params[4])
blockType = int(params[5])
blockData = int(params[6])
points = self.getLinePoints(x1, z1, x2, z2)
log.debug(points)
for p in points:
self.setBlock([p[0], y, p[1], blockType, blockData, ''])
return ''
# plots a circles point coords using Bresenham's circle algorithm (also known as a midpoint circle algorithm)
# based on code from http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm#Python
# note: y refers to usual cartesian x,y coords. Not the minecraft coords where y is the veritical axis
def getCirclePoints(self, x0, y0, radius):
log.debug('getCirclePoints with: {} {} {}'.format(x0, y0, radius))
points = []
x = 0
y = radius
f = 1 - radius
ddf_x = 1
ddf_y = -2 * radius
x = 0
y = radius
points.append((x0, y0 + radius))
points.append((x0, y0 - radius))
points.append((x0 + radius, y0))
points.append((x0 - radius, y0))
while x < y:
if f >= 0:
y -= 1
ddf_y += 2
f += ddf_y
x += 1
ddf_x += 2
f += ddf_x
points.append((x0 + x, y0 + y))
points.append((x0 - x, y0 + y))
points.append((x0 + x, y0 - y))
points.append((x0 - x, y0 - y))
points.append((x0 + y, y0 + x))
points.append((x0 - y, y0 + x))
points.append((x0 + y, y0 - x))
points.append((x0 - y, y0 - x))
return points
# builds a circle using Bresenham's circle algorithm (also known as a midpoint circle algorithm)
# plots using setBlock
def setCircle(self, params):
log.info('invoke setCircle with params: {} {} {} {} {}'.format(params[0], params[1], params[2], params[3], params[4]))
log.debug(params)
x1 = int(params[0])
z1 = int(params[1])
r = int(params[2])
y = int(params[3])
blockType = int(params[4])
blockData = int(params[5])
points = self.getCirclePoints(x1, z1, r)
log.debug(points)
for p in points:
self.setBlock([p[0], y, p[1], blockType, blockData, ''])
return ''
def postToChat(self, params):
log.info('post to chat: %s', urllib.unquote(params[0]))
mc.postToChat(urllib.unquote(params[0]))
return ''
def playerPosToChat(self, params):
log.info('playerPos to chat')
playerPos = mc.player.getTilePos()
log.debug(playerPos)
#playerPos = minecraft.Vec3(int(playerPos.x), int(playerPos.y), int(playerPos.z))
log.debug(playerPos)
posStr = ("x {0} y {1} z {2}".format(str(playerPos.x), str(playerPos.y), str(playerPos.z)))
log.debug(posStr)
mc.postToChat(urllib.unquote(posStr))
return ''
def cross_domain(self, params):
# not needed for offline editor, only online webeditor
log.info('need to return cross_domain.xml') # needed for scratch Flash issues
return ''
def reset_all(self, params):
log.info('trying to reset')
return ''
def getPlayerPos(self, params): # doesn't support metadata
log.info('invoke getPlayerPos: {}'.format(params[0]))
playerPos = mc.player.getTilePos()
#Using your players position
# - the players position is an x,y,z coordinate of floats (e.g. 23.59,12.00,-45.32)
# - in order to use the players position in other commands we need integers (e.g. 23,12,-45)
# - so we use getTilePos() which returns the integers
log.debug(playerPos)
# I'm sure theres a more pythony way to get at the vector elements but...
coord = params[0];
coordVal = 0;
if (coord == 'x'):
coordVal = playerPos.x
if (coord == 'y'):
coordVal = playerPos.y
if (coord == 'z'):
coordVal = playerPos.z
return str(coordVal)
# getBlock calls getBlockWithData function
def getBlock(self, params):
log.info ('getBlock: {0}'.format(params))
x = int(params[1])
y = int(params[2])
z = int(params[3])
if (params[4] == 'rel'): # set the block relative to the player
playerPos = mc.player.getTilePos()
x += playerPos.x
y += playerPos.y
z += playerPos.z
blockData = mc.getBlockWithData(x, y, z)
log.info ('blockData: %s', blockData)
if params[0] == 'data':
return str(blockData.data)
else:
return str(blockData.id)
# pollBlockHits calls pollBlockHits function
# currently only returns the first block in the period between polls
# requires that polling is enabled to check
# TODO: refactor to return multiple blocks
def pollBlockHits(self, params):
log.info ('pollBlockHits: {0}'.format(params))
blockHits = mc.events.pollBlockHits()
log.info ('blockHits: %s', blockHits)
if blockHits:
return str(1)
return str(0)
# from original version for scratch2
# currently unused
def pollEvents(self, params):
global pollInc, pollLimit, prevPosStr
pollInc += 1
log.debug('poll: {} {}'.format(pollInc, prevPosStr))
if (prevPosStr != "") and (pollInc % pollLimit != 0):
log.debug("don't call mc")
return prevPosStr
log.debug("call mc")
playerPos = mc.player.getPos()
#Using your players position
# - the players position is an x,y,z coordinate of floats (e.g. 23.59,12.00,-45.32)
# - in order to use the players position in other commands we need integers (e.g. 23,12,-45)
# - so round the players position
# - the Vec3 object is part of the minecraft class library
playerPos = minecraft.Vec3(int(playerPos.x), int(playerPos.y), int(playerPos.z))
# posStr = ("playerPos/x {0}\r\nplayerPos/y {1}\r\nplayerPos/z {2}".format(str(playerPos.x), str(playerPos.y), str(playerPos.z)))
# posStr = ("{0}".format(str(playerPos.x)))
log.debug(playerPos)
return playerPos.x
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Credentials', 'true')
# deal with the CORS issue
self.send_header('Access-Control-Allow-Origin', 'http://scratchx.org')
#self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header("Access-Control-Allow-Headers", "X-Requested-With, Content-type")
def do_GET(self):
global mc
cmds = {
"poll" : self.pollEvents,
"postToChat" : self.postToChat,
"setBlock" : self.setBlock,
"setBlocks" : self.setBlocks,
"setPlayerPos" : self.setPlayerPos,
"playerPosToChat" : self.playerPosToChat,
"setLine" : self.setLine,
"setCircle" : self.setCircle,
"cross_domain.xml" : self.cross_domain,
"reset_all" : self.reset_all,
"getPlayerPos" : self.getPlayerPos,
"getBlock" : self.getBlock,
"pollBlockHit" : self.pollBlockHits,
}
parsed_path = urlparse.urlparse(self.path)
message_parts = []
message_parts.append('')
cmdpath = parsed_path[2].split('/')
handler = cmds[cmdpath[1]]
pollResp = handler(cmdpath[2:])
log.debug ("pollResp: {0}".format(pollResp))
message_parts.append(pollResp)
message = '\r\n'.join(message_parts)
self.send_response(200)
# deal with the CORS issue
self.send_header('Access-Control-Allow-Origin', 'http://scratchx.org')
self.end_headers()
self.wfile.write(message)
return
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='mcpi-scratch is a Scratch2 extension helper app to allow Scratch programs to manipulate Minecraft through the Pi protocol')
parser.add_argument('-m', action="store", dest="host", help="hostname/IP for the machine running Minecraft. Default is localhost")
#parser.add_argument('-p', action="store", dest="port", type=int, help="port for the machine running Minecraft with the Pi protocol enabled. Default is 4711")
args = parser.parse_args()
log.info(args)
# nasty stuff to slow down the polling that comes from scratch.
# from the docs, sratch is polling at 30 times per second
# updating the player pos that often is causing the app to choke.
# use these vars to only make the call to MC every pollMax times - 15
# maybe change this to a cmd-line switch
pollInc = 0
pollLimit = 15
prevPosStr = ""
host = args.host or "localhost"
connected = False
while (not connected):
try:
mc = minecraft.Minecraft.create(host)
connected = True
except:
print("Timed out connecting to a Minecraft MCPI server (" + host + ":4711). Retrying in "+ str(MCPI_CONNECT_TIMEOUT) +" secs ... Press CTRL-C to exit.")
time.sleep( MCPI_CONNECT_TIMEOUT )
from BaseHTTPServer import HTTPServer
server = HTTPServer(('localhost', 4715), GetHandler)
log.info('Starting server, use <Ctrl-C> to stop')
server.serve_forever()