很抱歉在过去的几周里我没能做到。我搬了家,换了新工作,所以这段时间没有机会参与挑战。
穆罕默德·s·安瓦尔 (mohammad s. anwar) 每周都会发出“每周挑战”,让我们所有人都有机会为两周的任务提出解决方案。我的解决方案首先用python编写,然后转换为perl。这对我们所有人来说都是练习编码的好方法。
挑战,我的解决方案
给定坐标,一个字符串,代表棋盘正方形的坐标,如下所示:

编写一个脚本,如果方块是亮的则返回 true,如果方块是暗的则返回 false。
这相对简单。我做的第一件事是检查提供的位置是否有效(第一个字符是 a-h,第二个字符在 1 到 8 之间)。
然后我检查第一个字母是否是 a、c、e 或 g 并且数字是偶数,或者第一个字母是 b、d、f 或 h 并且数字是奇数,返回 true。否则返回 false。
def check_color(coords: str) -> bool:
if not re.search('^[a-h][1-8]$', coords):
raise valueerror('not a valid chess coordinate!')
if coords[0] in ('a', 'c', 'e', 'g') and int(coords[1]) % 2 == 0:
return true
if coords[0] in ('b', 'd', 'f', 'h') and int(coords[1]) % 2 == 1:
return true
return false
$ ./ch-1.py d3 true $ ./ch-1.py g5 false $ ./ch-1.py e6 true
国际象棋中的马可以从当前位置移动到两行或两列加一列或一行之外的任意方格。所以在下图中,如果它以s开头,它可以移动到任何标记为e的方块。

编写一个脚本,以起始位置和结束位置为基础,并计算所需的最少移动次数。
这个更详细。我从以下变量开始:
def knights_move(start_coord: str, end_coord: str) -> int:
for coord in (start_coord, end_coord):
if not re.search('^[a-h][1-8]$', coord):
raise valueerror(
f'the position {coord} is not a valid chess coordinate!')
deltas = ([2, 1], [2, -1], [-2, 1], [-2, -1],
[1, 2], [1, -2], [-1, 2], [-1, -2])
coords = [convert_coord_to_list(start_coord)]
target = convert_coord_to_list(end_coord)
moves = 1
seen = []
然后我有一个当前坐标列表和增量列表的双循环。设置一个变量 new_pos 代表骑士的新坐标。如果这导致了棋盘之外的位置或我们已经去过的坐标,我会跳过它。如果它落在目标上,我将返回移动值。
循环结束后,我将坐标列表重置为通过迭代收集的坐标,并将移动值加一。这一直持续到我们到达目标坐标。
while true:
new_coords = []
for coord in coords:
for delta in deltas:
new_pos = (coord[0] + delta[0], coord[1] + delta[1])
if not 0 < new_pos[0] < 9 or not 0 < new_pos[1] < 9 or new_pos in seen:
continue
if new_pos == target:
return moves
new_coords.append(new_pos)
seen.append(new_pos)
coords = new_coords
moves += 1
$ ./ch-2.py g2 a8 4 $ ./ch-2.py g2 h2 3
以上就是关于棋盘的一个的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号