如何解决如何在python中的启动框的邻居中执行循环以执行操作?
我使用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"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。