首页 > 解决方案 > 如何避免重复几乎相同的代码块?

问题描述

我正在尝试编写一个名为 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

我想知道是否有一种方法可以实现一种方法的功能或 Python 可以提供的任何方法来在一个循环中简化上面的代码,并根据需要调用它。

作为一个类比,我想到了来自 Lisp 的宏,它允许这样做。

谢谢

标签: pythonpython-3.x

解决方案


推荐阅读