python
import random
# 定义方块的类型
BLOCK_TYPES = ["stone", "dirt", "grass", "wood", "diamond", "gold"]
# 方块的属性
class Block:
def __init__(self, type_, hardness):
self.type = type_
self.hardness = hardness
# 游戏世界的大小
WORLD_SIZE = 10
# 玩家类
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
def move_up(self):
if self.y > 0:
self.y -= 1
def move_down(self):
if self.y < WORLD_SIZE - 1:
self.y += 1
def move_left(self):
if self.x > 0:
self.x -= 1
def move_right(self):
if self.x < WORLD_SIZE - 1:
self.x += 1
def place_block(self, world, block_type):
if 0 <= self.x < WORLD_SIZE and 0 <= self.y < WORLD_SIZE:
world[self.x][self.y] = Block(block_type, random.randint(1, 10)) # 随机设置方块硬度
def break_block(self, world):
if 0 <= self.x < WORLD_SIZE and 0 <= self.y < WORLD_SIZE:
if world[self.x][self.y] is not None:
block = world[self.x][self.y]
if random.randint(1, 10) > block.hardness: # 模拟破坏方块的概率
world[self.x][self.y] = None
# 初始化游戏世界
world = [[None for _ in range(WORLD_SIZE)] for _ in range(WORLD_SIZE)]
# 随机生成初始的方块
for x in range(WORLD_SIZE):
for y in range(WORLD_SIZE):
world[x][y] = Block(random.choice(BLOCK_TYPES), random.randint(1, 10)) # 初始化方块时设置硬度
# 创建玩家,初始位置在世界中心
player = Player(WORLD_SIZE // 2, WORLD_SIZE // 2)
# 打印游戏世界的函数
def print_world():
for row in world:
print(" ".join([str(block.type if block else "Empty") for block in row]))
# 游戏主循环
while True:
print_world()
action = input("请选择操作(w:上,s:下,a:左,d:右,p:放置方块,b:破坏方块,q:退出): ")
if action == 'w':
player.move_up()
elif action =='s':
player.move_down()
elif action == 'a':
player.move_left()
elif action == 'd':
player.move_right()
elif action == 'p':
block_type = input("请输入要放置的方块类型: ")
player.place_block(world, block_type)
elif action == 'b':
player.break_block(world)
elif action == 'q':
break
这个修改后的代码增加了玩家的移动操作、方块的硬度属性以及更丰富的用户交互。可以根据需要继续扩展和完善它。
点赞破40,光速更新!
<( ̄ c ̄)y▂
标签:self,move,更新,WORLD,world,block,SIZE From: https://blog.csdn.net/TtCoffee_2025/article/details/144932436