while循环的多个条件

时间:2016-10-31 05:32:24

标签: python

我正在编写一个函数来检查跳棋是否可以进行跳跃动作,并且当它无法跳跃时停止,所以我写道:

def checkJump(x,y,count,incr):
player = board[x][y]
count = 0

jumpleft = (board[x+incr][y+incr] != player) and (board[x+incr][y+incr] != '') and (board[x+(incr*2)][y+(incr*2)] == '') and 0 <= x <= 7 and 0 <= y <= 7 and 0 and 0 <= x+incr <= 7 and 0 <= x+(incr*2) <= 7 and 0 <= y+(incr*2) <= 7

jumpright = (board[x+incr][y-incr] != player) and (board[x+incr][y-incr] != '') and (board[x+(incr*2)][y-(incr*2)] == '') and 0 <= x <= 7 and 0 <= y <= 7 and 0 and 0 <= x+incr <= 7 and 0 <= x+(incr*2) <= 7 and 0 <= y-(incr*2) <= 7

while jumpleft or jumpright:    
    while jumpleft:
        x += incr*2
        y += incr*2
        count += 1
        jumpleft = (board[x+incr][y+incr] != player) and (board[x+incr][y+incr] != '') and (board[x+(incr*2)][y+(incr*2)] == '') and 0 <= x <= 7 and 0 <= y <= 7 and 0 and 0 <= x+incr <= 7 and 0 <= x+(incr*2) <= 7 and 0 <= y+(incr*2) <= 7

    while jumpright:
        x += incr*2
        y -= incr*2
        count += 1
        jumpright = (board[x+incr][y-incr] != player) and (board[x+incr][y-incr] != '') and (board[x+(incr*2)][y-(incr*2)] == '') and 0 <= x <= 7 and 0 <= y <= 7 and 0 and 0 <= x+incr <= 7 and 0 <= x+(incr*2) <= 7 and 0 <= y-(incr*2) <= 7

    jumpleft = (board[x+incr][y+incr] != player) and (board[x+incr][y+incr] != '') and (board[x+(incr*2)][y+(incr*2)] == '') and 0 <= x <= 7 and 0 <= y <= 7 and 0 and 0 <= x+incr <= 7 and 0 <= x+(incr*2) <= 7 and 0 <= y+(incr*2) <= 7

    jumpright = (board[x+incr][y-incr] != player) and (board[x+incr][y-incr] != '') and (board[x+(incr*2)][y-(incr*2)] == '') and 0 <= x <= 7 and 0 <= y <= 7 and 0 and 0 <= x+incr <= 7 and 0 <= x+(incr*2) <= 7 and 0 <= y-(incr*2) <= 7
return x,y,count    

但是,检查条件过于冗余,多个条件与and相关联。是否有更好的方法为while循环编写多个条件,而只是用and链接它们?非常感谢您的回答

2 个答案:

答案 0 :(得分:0)

也许你可以定义两个返回True或False的检查函数:

def jumpleft(x, y, board, incr):
    return (board[x+incr][y+incr] != player) and (board[x+incr][y+incr] != '') and (board[x+(incr*2)][y+(incr*2)] == '') and 0 <= x <= 7 and 0 <= y <= 7 and 0 and 0 <= x+incr <= 7 and 0 <= x+(incr*2) <= 7 and 0 <= y+(incr*2) <= 7

def jumpright(x, y, board, incr):
    return (board[x+incr][y-incr] != player) and (board[x+incr][y-incr] != '') and (board[x+(incr*2)][y-(incr*2)] == '') and 0 <= x <= 7 and 0 <= y <= 7 and 0 and 0 <= x+incr <= 7 and 0 <= x+(incr*2) <= 7 and 0 <= y-(incr*2) <= 7

然后打电话给他们获取价值。这将使您的代码更具可读性。

答案 1 :(得分:0)

由于您对游戏编程感兴趣,我建议使用pygame。如果您不感兴趣,我建议您更换一些&#34;和&#34;具有条件&#34; if语句&#34;的赋值运算符。它们具有相同的用途,更具可读性。