如何解决为文件中字符的特定位置创建字典
我正尝试在文件中搜索#,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
解决方法
您可以通过dictionary[key] = value
将值设置为字典中的键。通过row
和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",char in enumerate(line):
if char in class_dict:
game_dict[(row,col)] = class_dict[char](char)
print(game_dict)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。