I am about to start writing a chess program using Tkinter/ Python and I am experimenting with coordinates for moves as I have never used them before. How can I get this code working as right now I get: NameError: name 'x' is not defined.Thanks in advance for the help.
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)
You need to add the proper offset to the current piece position, and return the list of possible legal positions.
maybe something along these lines:
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)]
For a knight in position (0, 0)
, the output is [(2, 1), (1, 2)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.