如何在此代码中使用坐标?

时间:2019-06-28 04:16:36

标签: python-3.x tkinter coordinates

我即将开始使用Tkinter / Python编写国际象棋程序,并且我正在尝试移动坐标,因为我以前从未使用过它们。我如何才能立即使该代码正常工作:NameError:未定义名称“ x”。感谢您的帮助。

movelist=[]
KNIGHTLIST=[(x+2,y+1),(x+2,y-1),(x-2,y+1),(x-2,y-1),(x+1,y+2),(x+1,y-2),(x-1,y+2),(x-1,y-2)]
index=0
pieceposition=(3,4)
newposition=(0,0)
for move in KNIGHTLIST:
    newposition=pieceposition+KNIGHTLIST[index] 

    movelist.append(newposition)
    index=index+1
print (movelist)

1 个答案:

答案 0 :(得分:0)

您需要在当前工作位置上添加适当的偏移量,并返回可能的合法位置列表。

也许符合以下几点:

def get_possible_knight_moves(pos):
    x, y = pos
    possible_moves = []
    for dx, dy in knight_offsets:
        new_pos = (x + dx, y + dy)
        if is_legal(new_pos):
            possible_moves.append(new_pos)
    return possible_moves

def is_legal(pos):
    x, y = pos
    return 0 <= x < 8 and 0 <= y < 8


knight_offsets = [(2, 1), (2, -1), (1, 2), (1, -2), (-2, 1), (-2, -1),(-1, 2),(-1, -2)]

pieceposition = (3 , 4)
movelist = get_possible_knight_moves(pieceposition)
print (movelist)

输出:

[(5, 5), (5, 3), (4, 6), (4, 2), (1, 5), (1, 3), (2, 6), (2, 2)]

对于(0, 0)位置的骑士,输出为[(2, 1), (1, 2)]