python - 如何避免重复几乎相同的代码块?
问题描述
我正在尝试编写一个名为 Djambi 的棋盘游戏,它的大部分棋子都可以像国际象棋中的皇后一样移动。我创建了一个列表来保存一个片段的所有有效目的地,可以是 8 个不同的方向,所以我使用了 8 个for
循环,但每个循环的代码几乎相同:
这是可能向右移动的循环:
count = 0
for j in range(y+1,9):
if P == 3 and count == 2:
break
if re.search(r'[■]',board[x][j]):
pos = str(x)+str(j)
destinations.append(pos)
elif re.search(r'\d', board[x][j]):
if re.search(r'' + chip[0], board[x][j]) or P == 1 or P == 0:
break
else:
pos = str(x)+str(j)
destinations.append(pos)
break
elif re.search(r'[░]',board[x][j]):
if P == 0:
pos = str(x)+str(j)
destinations.append(pos)
break
else:
break
else:
if P == 2:
pos = str(x)+str(j)
destinations.append(pos)
else:
continue
count += 1
向左移动的循环可以用上面的那个来简化,但问题是向上移动的循环
count = 0
for i in range(x+1,9):
if P == 3 and count == 2:
break
if re.search(r'[■]',board[i][y]):
pos = str(i)+str(y)
destinations.append(pos)
elif re.search(r'[\d]',board[i][y]):
if re.search(r'' + chip[0], board[i][y]) or P == 1 or P == 0:
break
else:
pos = str(i)+str(y)
destinations.append(pos)
break
elif re.search(r'[░]',board[i][y]):
if P == 0:
pos = str(i)+str(y)
destinations.append(pos)
break
else:
break
else:
if P == 2:
pos = str(i)+str(y)
destinations.append(pos)
else:
continue
count += 1
和向下,因为变化的变量顺序不同,对于对角线运动也是如此:
count = 0
for i,j in zip( range(x+1,9) , range(y+1,9) ):
if P == 3 and count == 2:
break
if re.search(r'[■]',board[i][j]):
pos = str(i)+str(j)
destinations.append(pos)
elif re.search(r'[\d]',board[i][j]):
if re.search(r'' + chip[0], board[i][j]) or P == 1 or P == 0:
break
else:
pos = str(i)+str(j)
destinations.append(pos)
break
elif re.search(r'[░]',board[i][j]):
if P == 0:
pos = str(i)+str(j)
destinations.append(pos)
break
else:
break
else:
if P == 2:
pos = str(i)+str(j)
destinations.append(pos)
else:
continue
count += 1
x
y
是芯片原位置的固定坐标i
并且j
是变量坐标board
是一个 9x9 维度的矩阵
我想知道是否有一种方法可以实现一种方法的功能或 Python 可以提供的任何方法来在一个循环中简化上面的代码,并根据需要调用它。
作为一个类比,我想到了来自 Lisp 的宏,它允许这样做。
谢谢
解决方案
推荐阅读
- r - R - 从数据集(波士顿住房数据集)中查找 1 个观测值的所有特征的百分位数
- python - 如何让我的飞机/敌人班级上下飞行
- r - 尝试移动刻度线并删除轴标题中的 X
- r - 为什么我会为“plot.margins”和“margins”获得不同的 AME?
- list - 方案-计算对数的程序(SICP ex 3.17)-我的解决方案正确吗?
- flutter - 我可以在一个 Flutter 插件项目中拥有多个 FlutterPlugin 吗?
- typescript - Redux Toolkit w TypeScript:如何解开 AsyncThunk 的类型
- c - 在 Linux libreadline 中解析带引号和双引号的行
- python-2.7 - 使用 pyspark 将每一行的一列作为单独的文件写入 hdfs
- javascript - 从 Chrome 扩展发出请求时,无法访问响应的 httpOnly(如“set-cookie”)标头