mcapibridge 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mc/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ from .minecraft import Minecraft, Vec3, PlayerPos, BlockHit, ChatPost
2
+
3
+ __all__ = [
4
+ "Minecraft",
5
+ "Vec3",
6
+ "PlayerPos",
7
+ "BlockHit",
8
+ "ChatPost",
9
+ ]
mc/minecraft.py ADDED
@@ -0,0 +1,455 @@
1
+ import socket
2
+ import math
3
+ import time
4
+ import base64
5
+ import wave
6
+ import struct
7
+
8
+ class AudioManager:
9
+ def __init__(self, mc):
10
+ self.mc = mc
11
+
12
+ def load_wav(self, target, audio_id, filepath):
13
+ with wave.open(filepath, 'rb') as wav:
14
+ channels = wav.getnchannels()
15
+ sample_width = wav.getsampwidth()
16
+ sample_rate = wav.getframerate()
17
+ frames = wav.readframes(wav.getnframes())
18
+
19
+ if channels == 2:
20
+ samples = struct.unpack(f'<{len(frames)//2}h', frames)
21
+ mono_samples = []
22
+ for i in range(0, len(samples), 2):
23
+ mono_samples.append((samples[i] + samples[i+1]) // 2)
24
+ frames = struct.pack(f'<{len(mono_samples)}h', *mono_samples)
25
+
26
+ if sample_width == 1:
27
+ samples = struct.unpack(f'{len(frames)}B', frames)
28
+ samples = [(s - 128) * 256 for s in samples]
29
+ frames = struct.pack(f'<{len(samples)}h', *samples)
30
+
31
+ b64_data = base64.b64encode(frames).decode('ascii')
32
+
33
+ chunk_size = 40000
34
+ chunks = [b64_data[i:i + chunk_size] for i in range(0, len(b64_data), chunk_size)]
35
+
36
+ for i, chunk in enumerate(chunks):
37
+ if i == 0:
38
+ self.mc._send(f"audio.load({target},{audio_id},{sample_rate},{chunk})")
39
+ else:
40
+ self.mc._send(f"audio.stream({target},{audio_id},{sample_rate},{chunk})")
41
+ time.sleep(0.02)
42
+
43
+ self.mc._send(f"audio.finishLoad({target},{audio_id})")
44
+
45
+ print(f"[Audio] Loaded {filepath}: {len(frames)} bytes, {sample_rate}Hz")
46
+
47
+ def load_raw(self, target, audio_id, pcm_data, sample_rate=44100):
48
+ b64_data = base64.b64encode(pcm_data).decode('ascii')
49
+
50
+ chunk_size = 40000
51
+ chunks = [b64_data[i:i + chunk_size] for i in range(0, len(b64_data), chunk_size)]
52
+
53
+ for i, chunk in enumerate(chunks):
54
+ if i == 0:
55
+ self.mc._send(f"audio.load({target},{audio_id},{sample_rate},{chunk})")
56
+ else:
57
+ self.mc._send(f"audio.stream({target},{audio_id},{sample_rate},{chunk})")
58
+ time.sleep(0.02)
59
+
60
+ self.mc._send(f"audio.finishLoad({target},{audio_id})")
61
+
62
+ def play(self, target, audio_id, volume=1.0, loop=False):
63
+ loop_str = "true" if loop else "false"
64
+ self.mc._send(f"audio.play({target},{audio_id},{volume},{loop_str})")
65
+
66
+ def play_at(self, audio_id, x, y, z, radius=32, volume=1.0):
67
+ self.mc._send(f"audio.playAt({audio_id},{x},{y},{z},{radius},{volume})")
68
+
69
+ def play_3d(self, target, audio_id, x, y, z, volume=1.0, rolloff=1.0):
70
+ self.mc._send(f"audio.play3d({target},{audio_id},{x},{y},{z},{volume},{rolloff})")
71
+
72
+ def pause(self, target, audio_id):
73
+ self.mc._send(f"audio.pause({target},{audio_id})")
74
+
75
+ def stop(self, target, audio_id):
76
+ self.mc._send(f"audio.stop({target},{audio_id})")
77
+
78
+ def unload(self, target, audio_id):
79
+ self.mc._send(f"audio.unload({target},{audio_id})")
80
+
81
+ def set_volume(self, target, audio_id, volume):
82
+ """(0.0 - 1.0)"""
83
+ self.mc._send(f"audio.volume({target},{audio_id},{volume})")
84
+
85
+ def generate_tone(self, target, audio_id, frequency=440, duration=1.0, sample_rate=44100):
86
+ import math
87
+
88
+ num_samples = int(sample_rate * duration)
89
+ samples = []
90
+
91
+ for i in range(num_samples):
92
+ t = i / sample_rate
93
+ value = int(32767 * math.sin(2 * math.pi * frequency * t))
94
+ samples.append(value)
95
+
96
+ pcm_data = struct.pack(f'<{len(samples)}h', *samples)
97
+ self.load_raw(target, audio_id, pcm_data, sample_rate)
98
+
99
+ def set_position(self, target, audio_id, x, y, z):
100
+ self.mc._send(f"audio.position({target},{audio_id},{x},{y},{z})")
101
+
102
+
103
+ class Vec3:
104
+ def __init__(self, x, y, z):
105
+ self.x, self.y, self.z = x, y, z
106
+ def __repr__(self): return f"Vec3({self.x:.2f}, {self.y:.2f}, {self.z:.2f})"
107
+ def __sub__(self, o): return Vec3(self.x-o.x, self.y-o.y, self.z-o.z)
108
+ def length(self): return math.sqrt(self.x**2 + self.y**2 + self.z**2)
109
+
110
+ class PlayerPos(Vec3):
111
+ def __init__(self, x, y, z, yaw, pitch):
112
+ super().__init__(x, y, z)
113
+ self.yaw = yaw
114
+ self.pitch = pitch
115
+
116
+ def __repr__(self):
117
+ return f"PlayerPos(x={self.x:.1f}, y={self.y:.1f}, z={self.z:.1f}, yaw={self.yaw:.1f}, pitch={self.pitch:.1f})"
118
+
119
+ def forward(self, distance=1.0):
120
+ yaw_rad = math.radians(self.yaw)
121
+ pitch_rad = math.radians(self.pitch)
122
+
123
+ vx = -math.sin(yaw_rad) * math.cos(pitch_rad)
124
+ vy = -math.sin(pitch_rad)
125
+ vz = math.cos(yaw_rad) * math.cos(pitch_rad)
126
+
127
+ return Vec3(self.x + vx * distance, self.y + vy * distance, self.z + vz * distance)
128
+
129
+ class ChatPost:
130
+ def __init__(self, name, message):
131
+ self.name = name
132
+ self.message = message
133
+
134
+ def __repr__(self):
135
+ return f"[{self.name}]: {self.message}"
136
+
137
+ class BlockHit:
138
+ def __init__(self, x, y, z, face, entityId, action):
139
+ self.pos = Vec3(x, y, z)
140
+ self.face = face
141
+ self.entityId = entityId
142
+ self.action = action # 1=Left,2=Right,101-105:Keyboard Action
143
+ if action == 1: self.type = "LEFT_CLICK"
144
+ elif action == 2: self.type = "RIGHT_CLICK"
145
+ elif action > 100: self.type = f"KEY_MACRO_{action - 100}"
146
+
147
+ class Minecraft:
148
+ def __init__(self, host="localhost", port=4711):
149
+ self.host = host
150
+ self.port = port
151
+ self.socket = None
152
+ self.file_reader = None
153
+ self.connected = False
154
+ self._connect()
155
+ self.audio = AudioManager(self)
156
+
157
+ def _connect(self):
158
+ try:
159
+ if self.socket:
160
+ try: self.socket.close()
161
+ except: pass
162
+
163
+ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
164
+ self.socket.settimeout(5)
165
+ self.socket.connect((self.host, self.port))
166
+
167
+ self.file_reader = self.socket.makefile('r', encoding='utf-8')
168
+ self.connected = True
169
+ print(f"[MCAPI] Connected ({self.host}:{self.port}).")
170
+ return True
171
+ except (ConnectionRefusedError, socket.timeout):
172
+ print("[MCAPI] Lost connection.Retry...")
173
+ self.connected = False
174
+ return False
175
+
176
+ def _send(self, cmd):
177
+ try:
178
+ if not self.connected:
179
+ if not self._connect(): return
180
+
181
+ self.socket.sendall((cmd + "\n").encode("utf-8"))
182
+ except (BrokenPipeError, ConnectionResetError, socket.timeout, OSError):
183
+ print("[MCAPI] Lost connection.Retry...")
184
+ if self._connect():
185
+ try:
186
+ self.socket.sendall((cmd + "\n").encode("utf-8"))
187
+ except:
188
+ print("[MCAPI] Retry failed.")
189
+
190
+ def _recv(self):
191
+ if not self.connected: return ""
192
+ try:
193
+ line = self.file_reader.readline()
194
+ if not line:
195
+ print("[MCAPI] Retry.")
196
+ self.connected = False
197
+ for i in range(3):
198
+ time.sleep(1)
199
+ if self._connect():
200
+ return self._recv()
201
+ return ""
202
+ return line.strip()
203
+ except (socket.timeout, OSError):
204
+ return ""
205
+
206
+ def postToChat(self, msg):
207
+ self._send(f"chat.post({msg})")
208
+
209
+ def runCommand(self, cmd):
210
+ if cmd.startswith("/"): cmd = cmd[1:]
211
+ self._send(f"server.runCommand({cmd})")
212
+
213
+ def setBlock(self, x, y, z, block_id, dimension=None):
214
+ if dimension:
215
+ self._send(f"world.setBlock({int(x)},{int(y)},{int(z)},{block_id},{dimension})")
216
+ else:
217
+ self._send(f"world.setBlock({int(x)},{int(y)},{int(z)},{block_id})")
218
+
219
+ def spawnEntity(self, x, y, z, entity_id, yaw=0.0, pitch=0.0, dimension=None):
220
+ if dimension:
221
+ self._send(f"world.spawnEntity({x},{y},{z},{entity_id},{yaw},{pitch},{dimension})")
222
+ else:
223
+ self._send(f"world.spawnEntity({x},{y},{z},{entity_id},{yaw},{pitch})")
224
+
225
+ return int(self._recv())
226
+
227
+ def spawnParticle(self, x, y, z, particle_id, count=10, dx=0.0, dy=0.0, dz=0.0, speed=0.0, dimension=None):
228
+ cmd = f"{x},{y},{z},{particle_id},{count},{dx},{dy},{dz},{speed}"
229
+ if dimension:
230
+ cmd += f",{dimension}"
231
+ self._send(f"world.spawnParticle({cmd})")
232
+
233
+ def setEntityVelocity(self, entity_id, vx, vy, vz):
234
+ self._send(f"entity.setVelocity({entity_id},{vx},{vy},{vz})")
235
+
236
+ def getDirectionVector(self,target=""):
237
+ pos = self.getPlayerPos(target=target)
238
+
239
+ self._send("player.getPos()")
240
+ data = self._recv().split(",")
241
+ if len(data) < 5: return Vec3(0,0,1)
242
+
243
+ yaw = float(data[3])
244
+ pitch = float(data[4])
245
+
246
+ yaw_rad = math.radians(yaw)
247
+ pitch_rad = math.radians(pitch)
248
+
249
+ vx = -math.sin(yaw_rad) * math.cos(pitch_rad)
250
+ vy = -math.sin(pitch_rad)
251
+ vz = math.cos(yaw_rad) * math.cos(pitch_rad)
252
+
253
+ return Vec3(vx, vy, vz)
254
+
255
+ def setEntityNoGravity(self, entity_id, enable=True):
256
+ val = "true" if enable else "false"
257
+ self._send(f"entity.setNoGravity({entity_id},{val})")
258
+
259
+ def getPlayerPos(self, target=""):
260
+ self._send(f"player.getPos({target})")
261
+ data = self._recv()
262
+ if not data: return PlayerPos(0,0,0,0,0)
263
+ # x, y, z, yaw, pitch
264
+ parts = data.split(",")
265
+ if len(parts) >= 5:
266
+ return PlayerPos(
267
+ float(parts[0]), float(parts[1]), float(parts[2]),
268
+ float(parts[3]), float(parts[4])
269
+ )
270
+ return PlayerPos(0,0,0,0,0)
271
+
272
+ def getOnlinePlayers(self):
273
+ self._send("world.getPlayers()")
274
+ d = self._recv()
275
+ if not d: return []
276
+ players = []
277
+ for item in d.split("|"):
278
+ parts = item.split(",")
279
+ if len(parts) == 2:
280
+ players.append({"name": parts[0], "id": int(parts[1])})
281
+ return players
282
+
283
+ def getPlayerDetails(self, target=""):
284
+ self._send(f"player.getDetails({target})")
285
+ d = self._recv()
286
+ if not d or "Error" in d: return None
287
+ p = d.split(",")
288
+ # Name,ID,Mode,HP,MaxHP,Food,HeldItem,Count
289
+ return {
290
+ "name": p[0],
291
+ "id": int(p[1]),
292
+ "mode": p[2],
293
+ "health": float(p[3]),
294
+ "max_health": float(p[4]),
295
+ "food": int(p[5]),
296
+ "held_item": p[6],
297
+ "held_count": int(p[7])
298
+ }
299
+
300
+ def getPlayerEntityId(self, name):
301
+ players = self.getOnlinePlayers()
302
+ for p in players:
303
+ if p['name'] == name:
304
+ return p['id']
305
+ return None
306
+
307
+ def getPlayerName(self, entity_id):
308
+ players = self.getOnlinePlayers()
309
+ for p in players:
310
+ if p['id'] == entity_id:
311
+ return p['name']
312
+ return None
313
+
314
+ def getInventory(self, target=""):
315
+ self._send(f"player.getInventory({target})")
316
+ d = self._recv()
317
+
318
+ if not d or "EMPTY" in d or "ERROR" in d: return []
319
+
320
+ items = []
321
+ for item_str in d.split("|"):
322
+ parts = item_str.split(":")
323
+ if len(parts) == 3:
324
+ items.append({
325
+ "slot": int(parts[0]),
326
+ "id": parts[1],
327
+ "count": int(parts[2])
328
+ })
329
+ elif len(parts) == 4:
330
+ items.append({
331
+ "slot": int(parts[0]),
332
+ "id": f"{parts[1]}:{parts[2]}",
333
+ "count": int(parts[3])
334
+ })
335
+ return items
336
+
337
+ def setHealth(self, target, amount):
338
+ self._send(f"player.setHealth({target},{amount})")
339
+
340
+ def setFood(self, target, amount):
341
+ self._send(f"player.setFood({target},{amount})")
342
+
343
+ def give(self, target, item_id, count=1):
344
+ self._send(f"player.give({target},{item_id},{count})")
345
+
346
+ def clearInventory(self, target, item_id=""):
347
+ self._send(f"player.clear({target},{item_id})")
348
+
349
+ def giveEffect(self, target, effect_name, duration_sec=30, amplifier=1):
350
+ self._send(f"player.effect({target},{effect_name},{duration_sec},{amplifier})")
351
+
352
+ def teleport(self, x, y, z, target=""):
353
+ if target:
354
+ self._send(f"player.teleport({target},{x},{y},{z})")
355
+ else:
356
+ self._send(f"player.teleport({x},{y},{z})")
357
+
358
+ def teleportEntity(self, entity_id, x, y, z):
359
+ self._send(f"entity.teleport({entity_id},{x},{y},{z})")
360
+
361
+ def pollBlockHits(self):
362
+ self._send("events.block.hits()")
363
+ d = self._recv()
364
+ hits = []
365
+ if not d: return hits
366
+ for item in d.split("|"):
367
+ p = item.split(",")
368
+ if len(p) >= 6:
369
+ hits.append(BlockHit(
370
+ int(p[0]), int(p[1]), int(p[2]),
371
+ int(p[3]), int(p[4]), int(p[5])
372
+ ))
373
+ return hits
374
+
375
+ def pollChatPosts(self):
376
+ """
377
+ [ChatPost(name='Steve', message='Hello'), ...]
378
+ """
379
+ self._send("events.chat.posts()")
380
+ data = self._recv()
381
+ posts = []
382
+ if not data: return posts
383
+
384
+ for item in data.split("|"):
385
+ parts = item.split(",", 1)
386
+ if len(parts) == 2:
387
+ posts.append(ChatPost(parts[0], parts[1]))
388
+ return posts
389
+
390
+ def setFlying(self, target, allow_flight=True, is_flying=True):
391
+ a = "true" if allow_flight else "false"
392
+ f = "true" if is_flying else "false"
393
+ self._send(f"player.setFlying({target},{a},{f})")
394
+
395
+ def setFlySpeed(self, target, speed=0.05):
396
+ # Default speed:0.05
397
+ self._send(f"player.setSpeed({target},true,{speed})")
398
+
399
+ def setWalkSpeed(self, target, speed=0.1):
400
+ # Default speed:0.1
401
+ self._send(f"player.setSpeed({target},false,{speed})")
402
+
403
+ def setGodMode(self, target, enable=True):
404
+ val = "true" if enable else "false"
405
+ self._send(f"player.setGod({target},{val})")
406
+
407
+ def getBlock(self, x, y, z, dimension=None):
408
+ cmd = f"world.getBlock({int(x)},{int(y)},{int(z)})"
409
+ if dimension: cmd = f"world.getBlock({int(x)},{int(y)},{int(z)},{dimension})"
410
+ self._send(cmd)
411
+ return self._recv()
412
+
413
+ def getEntities(self, x, y, z, radius=10, dimension=None):
414
+ """
415
+ [{'id': 123, 'type': 'zombie', 'pos': Vec3}, ...]
416
+ """
417
+ cmd = f"world.getEntities({x},{y},{z},{radius})"
418
+ if dimension: cmd = f"world.getEntities({x},{y},{z},{radius},{dimension})"
419
+ self._send(cmd)
420
+ data = self._recv()
421
+ if not data: return []
422
+
423
+ entities = []
424
+ for item in data.split("|"):
425
+ # ID,Type,X,Y,Z
426
+ p = item.split(",")
427
+ if len(p) >= 5:
428
+ entities.append({
429
+ "id": int(p[0]),
430
+ "type": p[1],
431
+ "pos": Vec3(float(p[2]), float(p[3]), float(p[4]))
432
+ })
433
+ return entities
434
+
435
+ def setSign(self, x, y, z, line1="", line2="", line3="", line4="", dimension=None):
436
+ l1 = line1.replace(",", ",")
437
+ l2 = line2.replace(",", ",")
438
+ l3 = line3.replace(",", ",")
439
+ l4 = line4.replace(",", ",")
440
+
441
+ cmd = f"world.setSign({int(x)},{int(y)},{int(z)},{l1},{l2},{l3},{l4})"
442
+ if dimension: cmd += f",{dimension}"
443
+ self._send(cmd)
444
+
445
+ def lookAt(self, target, x, y, z):
446
+ self._send(f"player.lookAt({target},{x},{y},{z})")
447
+
448
+ def setEntityNbt(self, entity_id, nbt_string):
449
+ self._send(f"entity.setNbt({entity_id},{nbt_string})")
450
+
451
+ def setBlockNbt(self, x, y, z, nbt_string, dimension=None):
452
+ cmd = f"block.setNbt({int(x)},{int(y)},{int(z)},{nbt_string})"
453
+ if dimension: cmd += f",{dimension}"
454
+ self._send(cmd)
455
+
@@ -0,0 +1,306 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcapibridge
3
+ Version: 0.2.1
4
+ Summary: Python libary for MCAPIBridge
5
+ Author: TaotianZhufang
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 TaotianZhufang
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Requires-Python: >=3.7
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Dynamic: license-file
32
+
33
+ # MCAPIBridge Python Libary
34
+
35
+ MCAPIBridge is a mod for Minecraft loaded with Fabric.This libary offers some ways to connect Minecraft with this mod in Python.
36
+
37
+ ## QuickStart
38
+
39
+ ### Install
40
+ Ensure your mod loaded.
41
+
42
+ **Please ensure you are using the latest libary.Now version is 0.2.1.**
43
+
44
+ Use pip to install this.
45
+ ```
46
+ pip install mcapibridge
47
+ ```
48
+ This is a simple example to connect.
49
+ ```
50
+ from mc import Minecraft
51
+ import time
52
+
53
+ # Default ip is localhost and port is 4711
54
+ # You can use mc = Minecraft(host=YOURIP,port=YOURPORT) to change
55
+ mc = Minecraft()
56
+
57
+ # Show a message
58
+ mc.postToChat("§aHello, Minecraft! Python is here.")
59
+ ```
60
+
61
+ ---
62
+
63
+ ## Usage
64
+
65
+ ### Basic
66
+
67
+ #### `postToChat(msg)`
68
+ Send a message to chat screen.
69
+ * **msg**: String message.Support `§` .You can check it on Minecraft wiki.
70
+
71
+ #### `runCommand(cmd)`
72
+ Run commands as Server.
73
+ * **cmd**: Srting command without '/'
74
+
75
+ Ex: `mc.runCommand("time set day")`
76
+
77
+ ---
78
+
79
+ ### World
80
+
81
+ #### `setBlock(x, y, z, block_id, dimension=None)`
82
+ Set a block at the point given.
83
+ * **x, y, z**: Int positions.
84
+ * **block_id**: String ID.If it is Minecraft vanilla,the ID can be written without `Minecraft:`. Ex:`"stone"`, `"diamond_block"`.Support other namespaces.
85
+ * **dimension**: Optional String target dimension/player name.
86
+
87
+ #### `getBlock(x, y, z, dimension=None)`
88
+ Gets the block ID at the specified coordinates.
89
+ * **x, y, z**: Int positions.
90
+ * **dimension**: Optional String target dimension/player name.
91
+ * **return**: String block ID.Ex.`"minecraft:grass_block"`.
92
+
93
+ #### `spawnEntity(x, y, z, entity_id, yaw=0.0, pitch=0.0, dimension=None)`
94
+ Spawn an entity at the point given.
95
+ * **entity_id**: String ID.If it is Minecraft vanilla,the ID can be written without `Minecraft:`. Ex:`"zombie"`, `"pig"`, `"lightning_bolt"`.Support other namespaces.
96
+ * **yaw**: Optional Int degree.Horizontal degree.
97
+ * **pitch**: Optional Int degree.Vertical degree.
98
+ * **dimension**: Optional String target dimension/player name.
99
+
100
+ #### `setEntityVelocity(entity_id, vx, vy, vz)`
101
+ Sets the velocity of an entity.
102
+ * **entity_id**: Int ID.
103
+ * **vx, vy, vz**: Double velocity components.
104
+
105
+ #### `setEntityNoGravity(entity_id, enable=True)`
106
+ Enables or disables gravity for an entity.
107
+ * **entity_id**: Int ID.
108
+
109
+ #### `getEntities(x, y, z, radius=10, dimension=None)`
110
+ Gets the block ID at the specified coordinates.
111
+ * **x, y, z**: Double positions.
112
+ * **radius**: Double search radius.
113
+ * **dimension**: Optional String target dimension/player name.
114
+ * **return**: List of Dicts: [{'id': 123, 'type': 'minecraft:zombie', 'pos': Vec3}, ...]
115
+
116
+ #### `spawnParticle(x, y, z, particle_id, count=10, dx=0.0, dy=0.0, dz=0.0, speed=0.0, dimension=None)`
117
+ Spawn particle at the point given.
118
+ * **particle_id**: String ID.If it is Minecraft vanilla,the ID can be written without `Minecraft:`. Ex:`"flame"`, `"heart"`.Support other namespaces.
119
+ * **count**: Int count.
120
+ * **dx, dy, dz**: Optional double diffusion ranges.(when count=0, it represents the direction vector)
121
+ * **speed**: Optional double speed.
122
+ * **dimension**: Optional String target dimension/player name.
123
+
124
+ #### `setSign(x, y, z, line1="", line2="", line3="", line4="", dimension=None)`
125
+ Sets the text on a sign block.
126
+ * **x, y, z**: Int positions.
127
+ * **line1-4**: String text for each line.
128
+ * **dimension**: Optional String target dimension/player name.
129
+
130
+ **The block at the position must already be a sign.**
131
+
132
+ #### `lookAt(target, x, y, z)`
133
+ Forces a player or entity to look at a specific coordinate.
134
+ * **target**: String player name or Entity ID.
135
+ * **x, y, z**: The coordinate to look at.
136
+ * *Example*: `mc.lookAt("Steve", 0, 100, 0)` forces Steve to look up.
137
+
138
+ #### `setEntityNbt(entity_id, nbt_string)`
139
+ Modifies the NBT data of an entity directly using JSON format.
140
+ * **entity_id**: Integer Entity ID.
141
+ * **nbt_string**: Valid SNBT string (e.g., `"{NoAI:1b, Glowing:1b}"`).
142
+ * *Note*: Useful for setting attributes like Scale in 1.20.6 (`{Attributes:[{Name:"generic.scale",Base:2.0d}]}`).
143
+
144
+ #### `setBlockNbt(x, y, z, nbt_string, dimension=None)`
145
+ Modifies the NBT data of a block entity (Tile Entity).
146
+ * **x, y, z**: Integer coordinates.
147
+ * **nbt_string**: Valid SNBT string.
148
+
149
+
150
+ ---
151
+
152
+ ### Audio
153
+
154
+ #### [Audio Doc](https://github.com/TaotianZhufang/MCAPIBridge/blob/main/Bridges/Python/PyAudio.MD)
155
+
156
+ ---
157
+
158
+ ### Info
159
+
160
+ #### `getOnlinePlayers()`
161
+ Get players' name online.
162
+ * **return**: Dict: `[{'name': 'Steve', 'id': 123}, ...]`.
163
+
164
+ #### `getPlayerPos(target="")`
165
+ Get player's position and yaw and pitch.
166
+ * **target**: String player name.
167
+ * **return**: Int x,y,z and Double yaw,pitch.
168
+
169
+ #### `getPlayerEntityId(name)`
170
+ Get player's ID.
171
+ * **name**: String player name.
172
+ * **return**: Int ID.
173
+
174
+ #### `getPlayerName(entity_id)`
175
+ Get player's ID.
176
+ * **entity_id**: Int ID.
177
+ * **return**: String player name.
178
+
179
+ #### `getPlayerDetails(target="")`
180
+ Get player's details.
181
+ * **target**: String player name.
182
+ * **return**: Dict including
183
+ * `name`: String player name
184
+ * `id`: Int ID
185
+ * `mode`: String gamemode
186
+ * `health`: Double health
187
+ * `max_health`: Double max health
188
+ * `food`: Int food
189
+ * `held_item`: String item held
190
+ * `held_count`: Int item held count
191
+
192
+ ---
193
+
194
+ ### State
195
+
196
+ #### `setHealth(target, amount)`
197
+ Set player's health.
198
+ * **target**: String player name.
199
+ * **amount**: Double health.
200
+
201
+ #### `setFood(target, amount)`
202
+ Set player's food.
203
+ * **target**: String player name.
204
+ * **amount**: Int food(0-20).
205
+
206
+ #### `giveEffect(target, effect_name, duration_sec=30, amplifier=1)`
207
+ Effect player.
208
+ * **effect_name**: String effect ID.Ex:`"speed"`,`"night_vision"`.
209
+ * **duration_sec**: Int seconds.
210
+ * **amplifier**: Int amplifier.
211
+
212
+ #### `setFlying(target, allow_flight=True, is_flying=True)`
213
+ Enable player to fly in survival mode.
214
+ * **target**: String player name.
215
+
216
+ #### `setFlySpeed(target, speed=0.05)`
217
+ Set flight speed.
218
+ * **target**: String player name.
219
+ * **speed**: Double speed.Default 0.05.
220
+
221
+ #### `setWalkSpeed(target, speed=0.1)`
222
+ Set walk speed.
223
+ * **target**: String player name.
224
+ * **speed**: Double speed.Default 0.1.
225
+
226
+ #### `setGodMode(target, enable=True)`
227
+ Enable invulnerability.
228
+ * **target**: String player name.
229
+
230
+ ---
231
+
232
+ ### Inventory
233
+
234
+ #### `getInventory(target="")`
235
+ Get player's inventory.
236
+ * **return**: List of Dicts.Every dict has `{'slot': block_ID, 'id': item_ID, 'count': item_count}`.
237
+
238
+ #### `give(target, item_id, count=1)`
239
+ Give player item.
240
+ * **item_id**: String item ID.
241
+ * **count**: Int count.
242
+
243
+ #### `clearInventory(target, item_id="")`
244
+ Clear inventory.
245
+ * **target**: String player name.
246
+ * **item_id**: String item ID.
247
+
248
+ ---
249
+
250
+ ### TP
251
+
252
+ #### `teleport(x, y, z, target="")`
253
+ TP player.
254
+ * **x, y, z**: Int target x,y,z.
255
+ * **target**: String player ID.
256
+
257
+ #### `teleportEntity(entity_id, x, y, z)`
258
+ TP entitie.
259
+ * **entity_id**: Int entity id.
260
+
261
+ ---
262
+
263
+ ### Events
264
+
265
+ #### `pollBlockHits()`
266
+ Get click events.
267
+ * **return**: List Class `[BlockHit1,BlockHit2,.....]`
268
+ * **pos**: Class Vec3
269
+ * Double x
270
+ * Double y
271
+ * Double z
272
+ * **face**: Int click face.
273
+ * **entityId**: Int ID of clicking on entity.
274
+ * **action**: Int action type:1--left click,2--right click,101-105--Keyboard pressed.(Bind keys at Minecraft settings)
275
+ * **type**: String action:"LEFT_CLICK" or "RIGHT_CLICK"
276
+
277
+ #### `pollChatPosts()`
278
+ Get player message events.
279
+ * **return**: List Class `[ChatPost1,ChatPost2,.....]`
280
+ * **name**: String player name.
281
+ * **message**: String message.
282
+
283
+ ---
284
+
285
+ ### Helper Methods
286
+
287
+ #### `getDirectionVector(target="")`
288
+ Calculates the direction vector based on a player's rotation. Useful for shooting projectiles.
289
+ * **target**: String player ID.
290
+ * **return**: Class `Vec3` normalized direction vector.
291
+
292
+ ---
293
+
294
+ ### Helper Classes
295
+
296
+ #### `Vec3`
297
+ Represents a 3D vector/coordinate.
298
+ * **properties**: `x`,`y`,`z`.
299
+ * **Methods**:
300
+ * **length()**: Returns vector length.
301
+
302
+ #### `PlayerPos`
303
+ **Inherits Vec3** Represents player position with rotation.
304
+ * **properties**: `x`,`y`,`z`,`yaw`,`pitch`.
305
+ * **Methods**:
306
+ * **forward(distance=1.0)**: Returns a new `Vec3` position at `distance` blocks ahead of the player's view.
@@ -0,0 +1,7 @@
1
+ mc/__init__.py,sha256=6TuAOkHXMgtW0yNeyMAcVxiqRR8BTMekzrkDnNqQ93k,172
2
+ mc/minecraft.py,sha256=ivPNQY8891CxP9DV2BN8R5JAKhxXnECQL3w0fKz1g8Q,16573
3
+ mcapibridge-0.2.1.dist-info/licenses/LICENSE,sha256=tg_NYNbCG6JoE2a-Y6UDqKyr7eRAVOwSsSY8IzO9Cqw,1092
4
+ mcapibridge-0.2.1.dist-info/METADATA,sha256=Fo85RMWKBX7KKLrFKpIaF-R48F4NU5_soNJSR3Fax2o,9884
5
+ mcapibridge-0.2.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
6
+ mcapibridge-0.2.1.dist-info/top_level.txt,sha256=mNvdbMTKH8yVJh_OZ544RPTdOb3iE8wpsosgMq2V_cM,3
7
+ mcapibridge-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TaotianZhufang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ mc