亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為文件中特定位置的字符創建字典

為文件中特定位置的字符創建字典

莫回無 2023-09-05 15:18:24
我正在嘗試在文件中搜索 #, M,K, O, D 的實例,并且對于每個實例,在字典中返回 {position(tuple), instance type(#, M,K, O, D)} 。我編寫了一個函數來查找文件中實例的坐標,但是我不確定如何使用此信息添加和更新整個字典。這是我到目前為止所擁有的:def init_game_information(dungeon_name="game1.txt"):        self._dungeon=load_game(dungeon_name)        game_dict={}        with open("game1.txt", "r") as file:            for line in file:                for row, line in enumerate(self._dungeon):                    for col, char in enumerate(line):                        if WALL in line:                            x=WALL                            y=get_positions(self, WALL)                            dict_WALL={y,x}                        game_dict.update(dict_WALL)                        if KEY in line:                            x=KEY                            y=get_positions(self, KEY)                            KEY={y,x}                        game_dict.update(dict_KEY)                        if DOOR in line:                            x=DOOR                            y=get_positions(self, DOOR)                            dict_DOOR={y,x}                        game_dict.update(dict_DOOR)                        if MOVE_INCREASE in line:                            x=MOVE_INCREASE                            y=get_positions(self, MOVE_INCREASE)                            dict_MOVE={y,x}                        game_dict.update(dict_MOVE)                            def get_positions(self, entity):    """ Returns a list of tuples containing all positions of a given Entity         type.    Parameters:        entity (str): the id of an entity.    Returns:        )list<tuple<int, int>>): Returns a list of tuples representing the         positions of a given entity id.    """    positions = []    for row, line in enumerate(self._dungeon):        for col, char in enumerate(line):            if char == entity:                positions.append((row,col))    return positions這是游戲文件/應返回內容的示例:
查看完整描述

1 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

您可以通過 為字典中的鍵設置值dictionary[key] = value。通過rowand定義一個鍵col并將其關聯到字典:


keys = [WALL, KEY, DOOR, MOVE_INCREASE]

game_dict = {}

with open("game1.txt", "r") as file:

    for row, line in enumerate(file):

        for col, char in enumerate(line):


            if char in keys:

                game_dict[(row, col)] = char

如果您有對象的類(Wall,Key,...),那么您可以執行以下操作:


class_dict = { WALL : Wall, KEY : Key, DOOR : Door, MOVE_INCREASE: MoveIncrease}


game_dict = {}

with open("game1.txt", "r") as file:

    for row, line in enumerate(file):

        for col, char in enumerate(line):


            if char in class_dict:

                game_dict[(row, col)] = class_dict[char](char)


print(game_dict)


查看完整回答
反對 回復 2023-09-05
  • 1 回答
  • 0 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號