如果移动是伪合法的,我正在创建一个返回True的函数。问题是,为了找出pawn是否在它的起始位置,我必须循环该行中的所有方块,看看pawn所在的方块是否在该范围内。有一个更好的方法吗 ?我可以以某种方式计算典当所在的行号或什么?
# Pawn.
if piece == PAWN:
if not from_piece & 8: # White pawn.
if start_point < end_point: # Can't move backwards.
return False
elif diff == 32 and start_point in range(96, 104) and not board[start_point - 16] and not board[end_point]:
pass # Valid case, skip next elif statement. Can move 2 spaces at the starting position.
elif diff != 16:
return False
else: # Black pawn.
if start_point > end_point: # Can't move backwards.
return False
elif diff == 32 and start_point in range(16, 24) and not board[end_point + 16] and not board[end_point]:
pass # Valid case, skip next elif statement. Can move 2 spaces at the starting position.
elif diff != 16:
return False
if diff == 16 and board[end_point]: # Can't move ahead one square if there's already a piece.
return False
elif (diff == 15 or diff == 17) and board[end_point]: # Can't move one step diagonal when there's no enemy piece.
return False
return True
我制作了程序,白色棋子的值为1,黑色棋子的值为9.空方格用0表示。
非常感谢你。
答案 0 :(得分:1)
您可能想重新考虑一下您的模型,它看起来有点不必要地复杂化了。但是,您可以进行整数除法而不是循环:
(...)
elif diff == 32 and start_point / 16 == 6 and not board[end_point + 16] and not board[end_point]:
(...)
elif diff == 32 and start_point / 16 == 1 and not board[end_point + 16] and not board[end_point]:
(...)
就我个人而言,我认为您的代码看起来像是用Python表示数据的典型C方法。这没有什么不对,但我怀疑大多数pythonistas会做类似定义board
类或提供一些实用方法的东西:
board = [...]
def xy288(field):
"""Converts from (col, row) to [0...127]"""
return field[0] * 16 + field[1]
def is_white(field):
board[xy288(field)] <=8
def row(field):
return field[0]
def col(field):
return field[1]
def is_pawn(field):
return board[xy288(field)] % 8 == PAWN
def is_empty(field):
return board[xy288(field)] == 0
def valid_move(start, end):
# use tuples for encoding start and end, ie. start = (4,7)
if is_pawn(start):
direction = 1 if is_white(start) else -1
if col(start) == col(end) and \
row(start) == row(end) + 2*direction and \
is_empty(end) and \
is_empty((row(start) + direction, col(start)):
pass
这个想法是使代码具有语义和自包含,即我不必查看如何定义板以理解valid_move的工作原理。请注意,Python中具有全局范围的变量可能非常棘手 - 即。在这个例子中它可以工作,但如果你更改或在函数中分配一个变量,它将自动采用本地范围。