我已经使用for loop和pygame创建了一个网格:

我还把它连接到一个二维数组上。我已经根据块将x,y转换为行和列。
现在绿色的块代表开始位置,我必须对它的邻居,即所有接触它的块(甚至是角块)执行操作。
我想知道是否有更有效的解决方案,因为目前我只是将它们逐个存储在列表中,然后对其执行操作。
就像一个循环或类似的东西。
为了得到每一个的行和列,它需要大量的代码,所以请帮助我是一个初学者。
到目前为止,我已经做了这样的事情(我知道这是最糟糕的方式)
self.neighboursx.append(self.start_point_column)
self.neighboursy.append(self.start_point_row - 1)
self.neighboursx.append(self.start_point_column + 1)
self.neighboursy.append(self.start_point_row - 1)
self.neighboursx.append(self.start_point_column + 1)
self.neighboursy.append(self.start_point_row)
self.neighboursx.append(self.start_point_column - 1)
self.neighboursy.append(self.start_point_row + 1)
self.neighboursx.append(self.start_point_column)
self.neighboursy.append(self.start_point_row + 1)
self.neighboursx.append(self.start_point_column - 1)
self.neighboursy.append(self.start_point_row + 1)发布于 2020-10-19 20:35:44
要遍历2D数组,您可以执行如下操作:
for col in range(number_of_columns:
for row in range(number_of_rows):
do_something(col, row)对于您的邻居检查功能:
def do_something(col, row): # e.g. count neighbours of a boolean 2D array dd
count = 0
for x in range(-1, 2): # -1, 0, 1
for y in range(-1, 2):
try:
if dd[col +x][row + y]:
count += 1
except IndexError: # cell is outside array
pass
# but we don't want to count ourselves,
if dd[col][row]:
count -= 1
# now do something with the count
…另外,欢迎使用Stack Overflow。请带上tour阅读有关How to Ask的内容。理解这一点将使您更容易获得有用的答案。
发布于 2020-10-20 05:19:13
创建邻居索引列表:
neighbours = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]分别
neighbours = [(i, j) for i in range(3) for j in range(3) if i != j]并在for循环中使用索引:
for x, y in neighbours:
col = self.start_point_column + x
row = self.start_point_row + y
if 0 <= col < columns and 0 <= row < rows:
# do something with "row" and "col" https://stackoverflow.com/questions/64423070
复制相似问题