2016-07-06 3 views
-1

私はキングの動き(チェス)を解決しようとしていました。私は王が座標の場合にのみ移動できることを知った-1 <= x1-x2 and y1-y2 <= 1。 私のコードは次のとおりです。私のif/elseが正しく動作しない

x1 = int(input())    #cuurent x-position 
y1 = int(input())    #current y-position 
x2 = int(input())    #estimated x-position 
y2 = int(input())    #estimated y-position 
if -1 <= x1-x2 and y1-y2 <= 1: #king can move to the x2-y2 from x1-y1 
    print('YES') 
else:       #king can't move to the x2-y2 from x1-y1 
    print('NO') 

私は私が見つけることができるすべての「YES」動くと正常に動作しますが、それはのようないくつかの「NO」に移動すると、動作しません:

×1 = 4 y1 = 4、x2 = 2、y2 = 6またはx1 = 4、y1 = 4、x2 = 4、y2 = 6

。なぜなら、なぜなら、4-4 = 0,4-6 = -2、-2は-1よりも小さいからです。座標間の絶対差だから1

以下であれば

+0

2は> = -1および-2 <= 1; 0 > = -1および-2 <= 1.あなたは 'いいえ、両方とも真です... – Li357

答えて

4

王が移動することができ、書き込み:

if abs(x1-x2) <= 1 and abs(y1-y2) <= 1: #king can move to the x2-y2 from x1-y1 
    print('YES') 
else:       #king can't move to the x2-y2 from x1-y1 
    print('NO') 

をこれは座標ますので、あなたが移動している座標より大きくても小さくてもかまいませんが、最大でも1で異なることがわかります。

関連する問題