如果语句在python中的if语句中用于国际象棋游戏

时间:2017-09-02 22:13:20

标签: python python-3.x

我正在尝试构建一些python脚本,如果有人在x位置开始,可以概述国际象棋游戏中可用的动作。我的代码目前如下:

import argparse, json

chessBoard = [[1, 1, 1, 1, 1, 1, 1, 1] for i in range(8)]

chess_map_from_alpha_to_index = {
    "b" : 0,
    "c" : 1,
    "d" : 2,
    "e" : 3,
    "f" : 4,
    "g" : 5,
    "h" : 6,
    "i" : 7
}

chess_map_from_index_to_alpha = {
    0: "b",
    1: "c",
    2: "d",
    3: "e",
    4: "f",
    5: "g",
    6: "h",
    7: "i"
}


def getRookMoves(pos, chessBoard):
    column, row = list(pos.strip().lower())
    row = int(row) - 1
    column = chess_map_from_alpha_to_index[column]
    i,j = row, column
    solutionMoves = []

    # Compute the moves in Rank
    for j in xrange(8):
        if j != column:
            solutionMoves.append((row, j))

    # Compute the moves in File
    for i in xrange(8):
        if i != row:
           solutionMoves.append((i, column))

    solutionMoves = ["".join([chess_map_from_index_to_alpha[i[1]], str(i[0] + 1)]) for i in solutionMoves]
    solutionMoves.sort()
    return solutionMoves

def getKnightMoves(pos, chessBoard):
    """ A function that returns the all possible moves
        of a knight stood on a given position
    """
    column, row = list(pos.strip().lower())
    row = int(row) - 1
    column = chess_map_from_alpha_to_index[column]
    i,j = row, column
    solutionMoves = []

    try:
        temp = chessBoard[i - 6][j + 1]
        solutionMoves.append([i - 6, j + 1])
    except:
        pass
    try:
        temp = chessBoard[i - 3][j + 2]
        solutionMoves.append([i - 3, j + 2])
    except:
        pass
    try:
        temp = chessBoard[i - 5][j + 3]
        solutionMoves.append([i - 5, j + 3])
    except:
        pass
    try:
        temp = chessBoard[i - 7][j + 4]
        solutionMoves.append([i - 7, j + 4])
    except:
        pass
    try:
        temp = chessBoard[i - 1][j + 5]
        solutionMoves.append([i - 1, j + 5])
    except:
        pass
    try:
        temp = chessBoard[i - 4][j + 6]
        solutionMoves.append([i - 4, j + 6])
    except:
        pass
    try:
        temp = chessBoard[i - 2][j + 7]
        solutionMoves.append([i - 2, j + 7])
    except:
        pass
    # Filter all negative values
    temp = [i for i in solutionMoves if i[0] >=0 and i[1] >=0]
    allPossibleMoves = ["".join([chess_map_from_index_to_alpha[i[1]], str(i[0] + 1)]) for i in temp]
    allPossibleMoves.sort()
    return allPossibleMoves

parser = argparse.ArgumentParser()
parser.add_argument("-p", "--piece", help="chess piece name: ex- rook, knight, pawn etc")
parser.add_argument("-l", "--location", help="chess notation string: ex- E4, D6 etc")
args = parser.parse_args()

piece = args.piece.strip().lower()
location = args.location.strip()
# According to the type of piece adjust function
if (piece == "rook"):
    print (json.dumps({"piece":piece,
                      "current_location": location,
                      "moves": getRookMoves(location, chessBoard)}))
elif (piece == "knight"):
    print (json.dumps({"piece":piece,
                      "current_location": location,
                      "moves": getKnightMoves(location, chessBoard)}))

但理想情况下,我希望将if elif json.dump保留在最后但修改try: temp = chessBoard[i - 5][j + 3] solutionMoves.append([i - 5, j + 3]) except: pass

部分,所以这也成为一个if语句。因此,如果一个人输入python main.py -p"骑士" -l" b8"然后代码读取`temp = chessBoard [i - 5] [j + 3]             solutionMoves.append([i - 5,j + 3])         除了:             pass``

将b8作为一个位置并根据它输出答案。

希望这是有道理的。感谢在这里给予的任何帮助。

2 个答案:

答案 0 :(得分:0)

您依靠list index out of range例外来触发您的尝试代码。如果您退后一步并想一想为什么抛出该异常,您可以将其重新用于所需的if语句。发生该异常是因为您的某个索引大于棋盘中的列表。你的任何一个方向的棋盘都是8个项目,所以你可以检查0和8:

if 0 <= i-3 < 8 and 0 <= j+2 < 8:
    solutionMoves.append([i - 3, j + 2])

之前必须使用额外负片过滤器的原因是负值是列表的有效索引值。你可以立刻摆脱它们。

您可能需要考虑创建一个列表,列出您正在检查的所有案例(例如(-6,1),( - 3,2)等)并将其嵌入if for for循环中以减少代码重复。像这样:

# possible_moves are moves relative to current location
possible_moves = [(2, -1), (2, 1), (-1, 2), (1, 2), (-2, -1), (-2, 1), (-1, -2), (1, -2)]
for move in possible_moves:
    new_loc = (i + move[0], j + move[1])
    if 0 <= new_loc[0] < 8 and 0 <= new_loc[1] < 8:
        solutionMoves.append(new_loc)

答案 1 :(得分:0)

您是否只是检查此举是否会让您离开董事会?你可以这样做:

rf = i - 6
cf = j + 1
if 0 <= rf < 8 and 0 <= cf < 8:
     solutionMoves.append((rf, cf))

虽然我可能遗漏了一些东西,但你可能想看看这个: How do I generate all of a knight's moves?