我尝试纠正一些执行此操作的代码,但关卡变得混乱(将图块绘制到屏幕上,但没有绘制到正确的位置)。我相信问题可能出在我循环图像列表并尝试创建一个字典的部分,其中每个图像都有一个整数键。 ` 等级转换器类: def init(self, json_file_path): self.json_file_path = json_file_path
def convert_json_to_integer_list(self):
with open(self.json_file_path, 'r') as file:
json_data = json.load(file)
layers = json_data["layers"]
if len(layers) > 0:
data = layers[0]["data"]
return [int(tile_id) for tile_id in data]
else:
return []
def load_sprite_sheet(self, sprite_sheet_path, tile_size):
self.sprite_sheet = pygame.image.load(sprite_sheet_path)
tile_width, tile_height = tile_size,tile_size
tile_images = []
tile_mapping = {0:""}
for y in range(0, self.sprite_sheet.get_height(), tile_height):
for x in range(0, self.sprite_sheet.get_width(), tile_width):
tile_images.append(self.sprite_sheet.subsurface(pygame.Rect(x, y, tile_width, tile_height)))
for index, image in enumerate(tile_images, start=1): #The part I think may be wrong
tile_mapping[index] = image
return tile_mapping
def draw_tiles(self, surface,path, tile_width, tile_height):
tile_list = self.convert_json_to_integer_list()
tile_dict = self.load_sprite_sheet(path,tile_width)
num_cols = surface.get_width() // tile_width
num_rows = len(tile_list) // num_cols
for i in range(num_rows):
for j in range(num_cols):
tile_index = i * num_cols + j
tile_value = tile_list[tile_index]
if tile_value in tile_dict:
if tile_value == 0:
pass
else:
tile_image = tile_dict[tile_value]
tile_image = pygame.transform.scale(tile_image, (tile_width, tile_height))
surface.blit(tile_image, (j * tile_width, i * tile_height))
`我还会附上 json 文件以防万一
{ "compressionlevel":-1,
"height":20,
"infinite":false,
"layers":[
{
"data":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 3, 1, 1, 1, 1, 1, 1, 0, 0, 5, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 0, 0, 5, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
"height":20,
"id":1,
"name":"Tile Layer 1",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":30,
"x":0,
"y":0
}],
"nextlayerid":2,
"nextobjectid":1,
"orientation":"orthogonal",
"renderorder":"right-down",
"tiledversion":"1.10.1",
"tileheight":16,
"tilesets":[
{
"firstgid":1,
"source":"TileMap.tsx"
}],
"tilewidth":16,
"type":"map",
"version":"1.10",
"width":30
}
我建议编写一个自定义类,它采用 json 级别并将其转换为表面(显然,每次迭代后将位置存储在每次增加高度或宽度的地方)
不用 OOP 也可以做到这一点,但随着时间的推移,你的代码会变得越来越糟,就像现在一样