簡體   English   中英

如何在 pygame 中讀取磁貼 map 的 a.csv 文件?

[英]How do I read a .csv file for a tile map in pygame?

我正在為我在 GMTK Game Jam 中制作的條目制作續集。 這是一個平台游戲,玩家必須通過隨機選擇的各種游戲模式的地圖,比如平台競賽、boss戰,以及我只能形容為躲避球但有一個巨大的殺手吃豆人。 為此,我想制作許多級別,並且在 python 腳本中慢慢編輯列表不會為此而削減它。 所以我想學習如何閱讀.csv 文件並使用它們創建一個使用許多圖塊的關卡。 但是我怎么會 go 關於這個?

到目前為止,我有一個主腳本、一個精靈腳本和一個關卡腳本。 最后一個里面有兩個測試級別圖,我想用各種.csv文件的文件夾替換它。 在我的主腳本中,我有一個游戲 class。 __init__方法中,我設置了從關卡腳本中提取的關卡列表,隨機選擇一個來加載,並在索引為某個值時循環遍歷它以從我的 sprites 腳本創建一個 sprite。

#Set tile map
        self.level = [levels.plat_lvl_1, levels.plat_lvl_2]

        self.tile_map = random.choice(self.level)

        for i in range(len(self.tile_map)):
            for j in range(len(self.tile_map[i])):
                if self.tile_map[i][j] == 1:
                    sprites.Tile(j * 32, i * 32, 1, self.tile_group)

                elif self.tile_map[i][j] == 2:
                    sprites.Tile(j * 32, i * 32, 2, self.tile_group, self.platform_group)

                elif self.tile_map[i][j] == 3:
                    sprites.Tile(j * 32, i * 32, 3, self.tile_group, self.platform_group)

                elif self.tile_map[i][j] == 4:
                    sprites.Tile(j * 32, i * 32, 4, self.tile_group, self.platform_group)

                elif self.tile_map[i][j] == 5:
                    self.player = sprites.Player(j * 32, i * 32, self.player_group, self.platform_group)

                elif self.tile_map[i][j] == 6:
                    sprites.Tile(j * 32, i * 32 - 32, 6, self.tile_group)

我將如何用 .csv 文件替換列表,以及我需要如何遍歷它或剝離它或其他什么才能正確創建我的關卡? 如果您需要, 這里是整個項目的鏈接

非常感謝!

-多米尼克。

我有這個 function 將 csv 映射轉換為 List[List[int]] 格式。

def convert_csv_to_2d_list(csv_file: str):
    tile_map = []
    with open(csv_file, "r") as f:
        for map_row in csv.reader(f):
            tile_map.append(list(map(int, map_row)))
    return tile_map

那么它的用法將是:

self.tile_map = convert_csv_to_2d_list(csv_file="csv_file_location.csv")
for row in range(len(self.tile_map)):
    for col in range(len(self.tile_map[row])):
        # specific codes follows here

你可以這樣做:

import csv

with open('level_file.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
   
    for row in csv_reader:
        for coloumn in range(len(row)):
            if row[coloumn] == 1:
                #do sprite stuff
                sprites.Tile(coloumn * 32, row * 32, 1, self.tile_group)

            elif row[coloumn] == 2:
                #etc
   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM