我大概用了这个标题,所以这里有一个解释: 我有两个类,Tile和Grid。 在图块中,我创建了基本图块格式及其位置,名称和项目。 在Grid中,我使用for循环来正确创建这些图块并添加信息并将其全部存储在“ grid”中 我想允许用户在网格中搜索其图块具有“名称”属性(与用户尝试搜索的属性相同)的图块,然后返回所有信息(x和y位置,名称”和“项目”属性)。
global grid
letters = ["A","B","C","D","E","F","G","H","I"]
class Tile:
def __init__(self, x, y, name=None, items="Empty"):
self.x = x
self.y = y
self.contents = {
"name": name,
"items": items
}
def __repr__(self):
return str(self.contents)
class Grid:
def __init__(self):
self.grid = []
self.resetGrid()
def resetGrid(self):
grid = [[Tile(x, y) for x in range(9)] for y in range(9)]
for n in range(9):
letter = letters[n]
for m in range(9):
grid[n][m].contents = {"name":letter + str(m+1),"items":"Empty"}
return grid
def printGrid(self):
for row in grid:
print()
print("-" * 44)
for tile in row:
name = tile.contents["name"]
#items = tile.contents["items"]
print(name, end=" | ")
print()
print("-" * 44)
def searchGrid(self):
grid = self.resetGrid()
print()
print("")
print("Please select which square you wish to see the information about.")
userinput = input("> ")
for name in tile.contents["name"]:
pring("k")
newgrid = Grid()
newgrid.printGrid()
#newgrid.resetGrid()
感谢您的帮助。
答案 0 :(得分:0)
仅在每个图块中搜索名称,直到找到它为止。这是您要找的吗?
def searchGrid(self):
grid = self.resetGrid()
print()
print("")
print("Please select which square you wish to see the information about.")
userinput = input("> ")
for row in self.grid:
for tile in row:
if tile.contents['name'] == userinput:
print(tile.contents)
#other things
break
还请注意拼写错误:
将pring
更改为print
用grid
方法将self.grid
更改为printGrid()
答案 1 :(得分:0)
letters = ["A","B","C","D","E","F","G","H","I"]
class Tile:
def __init__(self, x, y, name=None, items="Empty"):
self.x = x
self.y = y
self.contents = {
"name": name,
"items": items
}
def __repr__(self):
return str(self.contents)
class Grid:
def __init__(self):
self.grid = []
self.resetGrid()
def resetGrid(self):
self.grid = [[Tile(x, y) for x in range(9)] for y in range(9)]
for n in range(9):
letter = letters[n]
for m in range(9):
self.grid[n][m].contents = {"name":letter + str(m+1),"items":"Empty"}
def printGrid(self):
for row in self.grid:
print()
print("-" * 44)
for tile in row:
name = tile.contents["name"]
#items = tile.contents["items"]
print(name, end=" | ")
print()
print("-" * 44)
def searchGrid(self):
print()
print("")
print("Please select which square you wish to see the information about.")
userinput = input("> ")
for n in range(9):
for m in range(9):
if userinput == self.grid[n][m].contents['name']:
print(self.grid[n][m].x)
print(self.grid[n][m].y)
print(self.grid[n][m].contents['name'])
print(self.grid[n][m].contents['items'])
newgrid = Grid()
newgrid.printGrid()
newgrid.searchGrid()