给定棋盘上两个皇后的位置,判断她们是否处于可以相互攻击的位置。
在国际象棋中,皇后可以攻击同一行、同一列或同一斜线上的棋子。
棋盘可以用一个 8×8 的数组表示。
所以,如果告诉你白皇后位于c5(从 0 开始索引,即第 2 列第 3 行),黑皇后位于f2(从 0 开始索引,即第 5 列第 6 行),那么这个局面就像这样:
你同样可以回答这两个皇后能否相互攻击。 在这个局面中,答案是肯定的,她们可以,因为两个皇后位于同一条斜线上。
棋盘图片由 habere-et-dispertire 使用 LaTeX 和 Ulrike Fischer 的 chessboard 宏包 制作。
有时需要抛出异常。抛出异常时,应始终附上有意义的错误消息,说明错误的来源。这会让代码更易读,也大大有助于调试。如果你知道错误来源属于某种特定类型,可以选择抛出某个内置错误类型,但仍应附上有意义的消息。
本练习要求你使用 raise 语句,在向Queen构造函数传入负数,或传入不是有效行或列的数值时,“抛出”ValueErrors。只有当你在raise异常的同时附上消息,测试才会通过。另外,如果传给can_attack()方法的两个皇后位于同一位置,你也应该raise一个ValueError。
要带着消息raise一个ValueError,请把消息写成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")