《Minecraft》(中文译名《我的世界》)简称MC,MC是一款沙盒建造游戏,玩家可以在一个三维世界里用各种方块建造或者破坏方块。
如何在Python里做一个我的世界?要用到Python里的3D游戏引擎Ursina.
from ursina import * #导入ursina模块
from ursina.prefabs.first_person_controller import FirstPersonController
from perlin_noise import PerlinNoise #随机地形算法柏林噪声模块
app=Ursina()
#加载图片文件
grass_texture=load_texture('assets/grass_block.png')
stone_texture=load_texture('assets/stone_block.png')
brick_texture=load_texture('assets/brick_block.png')
dirt_texture=load_texture('assets/dirt_block.png')
sky_texture=load_texture('assets/skybox.png')
arm_texture=load_texture('assets/arm_texture.png')
punch_sound=Audio('assets/punch_sound',loop=False,autoplay=False)
block_pick=1
#关闭FPS显示和关闭按键显示
window.fps_counter.enabled=False
window.exit_button.visible=False
scene.fog_color=color.white
scene.fog_density=0.04
def input(key):
if key =='q' or key=='escape':
quit()
#定义玩家
player=FirstPersonController()
#更新
def update():
global block_pick
#检测并切换手持方块
if held_keys['1']:block_pick=1
if held_keys['2']:block_pick=2
if held_keys['3']:block_pick=3
if held_keys['4']:block_pick=4
#检测手部按键和运动
if held_keys['left mouse'] or held_keys['right mouse']:
hand.active()
else:
hand.passive()
#如果玩家掉进虚空就传送上来
if player.position[1] < (-5):
player.position = Vec3(0, 0.25, 0)
#定义方块
class Block(Button):
def __init__(self,position=(0,0,0),texture=grass_texture):
super().__init__(
parent=scene,
position=position,
model='assets/block',
origin_y=0.5,
texture=texture,
color=color.color(0,0,random.uniform(0.9,1)),
#highlight_color=color.green,
scale=0.5
)
def input(self,key):
if self.hovered:
if key=='right mouse down':
punch_sound.play()
if
block_pick==1:block=Block(position=self.position+mouse.normal,texture=grass_texture)
if block_pick==2:block=Block(position=self.position+mouse.normal,texture=stone_texture)
if block_pick==3:block=Block(position=self.position+mouse.normal,texture=brick_texture)
if block_pick==4:block=Block(position=self.position+mouse.normal,texture=dirt_texture)
if key=='left mouse down':
punch_sound.play()
destroy(self)
#定义天空
class Sky(Entity):
def __init__(self):
super().__init__(
parent=scene,
model='sphere',
texture=sky_texture,
scale=150,
double_sided=True
)
#定义手
class Hand(Entity):
def __init__(self):
super().__init__(
parent=camera.ui,
model='assets/arm',
texture=arm_texture,
scale=0.2,
rotation=Vec3(150,-10,0),
position=Vec2(0.4,-0.6)
)
def active(self):
self.position=Vec2(0.3,-0.5)
def passive(self):
self.position=Vec2(0.4,-0.6)
noise=PerlinNoise(octaves=3,seed=2023)
scale=24
for z in range(50):
for x in range(50):
block=Block(position=(x,0,z))
block.y=floor(noise([x/scale,z/scale])*8) #用柏林噪声算法调整方块的x坐标
sky=Sky()
hand=Hand()
app.run()
图片文件链接:百度网盘