问题描述
我使用for循环和pygame创建了一个网格:
,我也将它连接到2D阵列。我已经根据块将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)
解决方法
要遍历2D数组,您可以执行以下操作:
fields: [
{
name: 'Field1',value: 'Value1',inline: true
},{
name: 'Field2',value: 'Value2',{
name: '\b',value: '\b',{
name: 'Field3',value: 'Value3',{
name: 'Field4',value: 'Value4',]
对于您的邻居检查功能:
for col in range(number_of_columns:
for row in range(number_of_rows):
do_something(col,row)
此外,欢迎使用Stack Overflow。请以tour并阅读有关How to Ask的信息。了解这一点将使其更容易获得有用的答案。
,创建邻居索引列表:
neighbours = [(-1,-1),(0,(1,(-1,0),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"