給定西洋棋棋盤上兩個皇后的位置,判斷它們的擺法是否讓彼此能互相攻擊。
在西洋棋中,皇后可以攻擊位於同一行、同一列或同一條對角線上的棋子。
棋盤可以用 8 乘 8 的陣列來表示。
所以,如果有人告訴你白色皇后在 c5(索引從 0 開始,也就是第 2 列、第 3 行),黑色皇后在 f2(第 5 列、第 6 行),你就能知道局面是這樣擺的:
你也可以回答這兩個皇后是否能互相攻擊。 在這個例子中,答案是肯定的,它們能互相攻擊,因為這兩個棋子位於同一條對角線上。
棋盤圖片由 habere-et-dispertire 使用 LaTeX 與 Ulrike Fischer 的 chessboard 套件 製作。
有時你會需要引發例外。這麼做的時候,一定要附上有意義的錯誤訊息,指出錯誤的來源。這能讓你的程式碼更容易閱讀,對除錯也有很大的幫助。如果你知道錯誤來源一定是某種類型,可以選擇引發其中一種內建錯誤型別,但仍然要附上有意義的訊息。
這個練習要求你使用 raise statement,在傳給Queen建構子的數字是負數,或不是有效的列或欄時「拋出」ValueError。只有在同時raise這個exception並附上訊息時,測試才會通過。如果傳給can_attack()方法的兩個皇后位在同一個位置,你也應該raise一個ValueError。
若要引發附有訊息的ValueErrors,請把訊息寫成exception型別的引數:
# if the row parameter is negative
raise ValueError("row not positive")
# if the row parameter is not on the defined board
raise ValueError("row not on board")
# if the column parameter is negative
raise ValueError("column not positive")
# if the column parameter is not on the defined board
raise ValueError("column not on board")
# if both the queens are on the same location
raise ValueError("Invalid queen position: both queens in the same square")