已满足while循环的指定条件,但不会停止

时间:2017-11-20 23:40:13

标签: python python-3.x

我正在尝试使用python龟创建一个Tic-Tac-Toe游戏,下面是功能“选择”的一小部分。

snapshot = ['', '', '', '', '', '', '', '', '']

列表“快照”不在函数内。

def choose():
    which_box = input('Which box? 1-9:')
    draw_xo = input('x or o?')

    if which_box == '1':
        if draw_xo == 'x':
            x(third / 2, third / 2)  # Function X has coordinates as parameters
            snapshot[0] = 'x'  # Assign x to an index in snapshot
        elif draw_xo == 'o':
            o(third / 2, third / 2)
            snapshot[0] = 'o'

因此,在用户连续获得三个方框以获胜后,即使满足获胜条件,下方函数内的循环仍会继续运行。在这个功能里面就是问题所在。

def check_if_won():
    # Create variables to store the various win conditions (cases)
    c1 = snapshot[0:2] == 'x' 
    c2 = snapshot[3:5] == 'x'  
    c3 = snapshot[6:8] == 'x' 
    c4 = snapshot[0] == 'x' and snapshot[3] == 'x' and snapshot[6] == 'x' 
    c5 = snapshot[1] == 'x' and snapshot[4] == 'x' and snapshot[7] == 'x'  
    c6 = snapshot[2] == 'x' and snapshot[5] == 'x' and snapshot[8] == 'x' 
    c7 = snapshot[0] == 'x' and snapshot[4] == 'x' and snapshot[8] == 'x'  
    c8 = snapshot[2] == 'x' and snapshot[4] == 'x' and snapshot[6] == 'x' 
    c9 = snapshot[0:2] == 'o'  
    c10 = snapshot[3:5] == 'o'  
    c11 = snapshot[6:8] == 'o' 
    c12 = snapshot[0] == 'o' and snapshot[3] == 'o' and snapshot[6] == 'o'  
    c13 = snapshot[1] == 'o' and snapshot[5] == 'o' and snapshot[7] == 'o'  
    c14 = snapshot[2] == 'o' and snapshot[5] == 'o' and snapshot[8] == 'o'  
    c15 = snapshot[0] == 'o' and snapshot[4] == 'o' and snapshot[8] == 'o'  
    c16 = snapshot[2] == 'o' and snapshot[4] == 'o' and snapshot[6] == 'o'  
    # Put variables in a list so I can iterate over them
    case_list = [c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16]
    for case in case_list:
        while case is False:
            choose()
    if case in case_list is True:  # This does not work
        print('Game over!')  # This never happens even when the conditions are true

我将每个win条件分配给一个变量,所以我可以在for循环中迭代它们。然后我检查了每个变量,看看其中一个是否为True。为什么上面的代码不起作用?我使用for循环错了吗?或者也许我尝试使用的方法无法实现我的目标?我也尝试过这样写:

for case in case_list:
    while not case:
        choose()
    if case:  # I have learned putting "is True" is unnecessary here
        print('Game over!')

但这也不起作用。

2 个答案:

答案 0 :(得分:0)

for case in case_list:
    while case is False:
        choose()

这将选择case_list中的第一个值,该值必须为c1,并且它将循环运行while,直到此条件为真。

您需要使用简单的for...while...循环替换while循环,以检查True

中是否有case_list
while True not in case_list:
    choose()

这应该有效!

答案 1 :(得分:0)

这些语句及其o合作伙伴必须始终评估为False

c1 = snapshot[0:2] == 'x' 
c2 = snapshot[3:5] == 'x'  
c3 = snapshot[6:8] == 'x' 

将3个字符的snapshot切片与单个字符进行比较;这些永远不会比较相等。尝试完整匹配:

c1 = snapshot[0:2] == 'xxx' 
c2 = snapshot[3:5] == 'xxx'  
c3 = snapshot[6:8] == 'xxx'

或者也许使用all函数

c1 = all(snapshot[i] == 'x' for i in range(0, 3) )
c2 = all(snapshot[i] == 'x' for i in range(3, 6) )
c3 = all(snapshot[i] == 'x' for i in range(6, 9) )