我有以下问题
在国际象棋中,象沿对角线移动,任意数量的方格。给定棋盘的两个不同方格,确定象是否可以一次从第一格走到第二格。
程序接收从 1 到 8 的四个数字作为输入,指定起始方 block 的列号和行号以及结束方 block 的列号和行号。如果主教可以一次从第一个方格走到第二个方格,程序应该输出 YES,否则输出 NO。
例如:
输入: 2个 3个 5个 6
输出:
是
假设单元格是从左到右、从下到上编号的,即左下角的单元格有列号 1 和行号 1,而右下角的单元格有列号 8 和行号 1。
我走了多远?
我设法检查主教是否沿对角线移动,但它可以移动任何对角线,所以这是不正确的。有人可以给我一些提示吗?
我的代码
initial_coord_x=int (input('enter the initial x'))
initial_coord_y=int (input('enter the initial y'))
final_coord_x=int (input('enter the final x'))
final_coord_y=int (input('enter the final y'))
if final_coord_x<=8 and final_coord_y<=8:
if final_coord_x < initial_coord_x and final_coord_y > initial_coord_y:
print ('you moved legally')
elif final_coord_x < initial_coord_x and final_coord_y < initial_coord_y:
print ('you moved legally')
elif final_coord_x > initial_coord_x and final_coord_y > initial_coord_y:
print ('you moved legally')
elif final_coord_x > initial_coord_x and final_coord_y < initial_coord_y:
print ('you moved legally')
else:
print ('no!')
else:
print ('illegal move, you moved outside the chessboard')
最佳答案
要检查主教移动(在现有单元格处)的可能性,只需检查水平位移的绝对值是否等于垂直位移的绝对值(因此两个位置位于同一对角线上)
dx = abs(final_coord_x - initial_coord_x)
dy = abs(final_coord_y - initial_coord_y)
if (dx == dy) and (dx > 0):
legal move
关于python - 对角线主教用 python 在棋盘上移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69523744/