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



我正在尝试使用python Turtle创建一个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'

因此,在A用户连续三个框以获胜后,即使满足了获胜条件,下面功能内部的循环仍保持运行。此功能内部是问题所在。

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

我将每个胜利条件分配给一个变量,因此我可以在for循环中迭代它们。然后,我检查了每个变量以查看其中一个是否为真。为什么上述代码不起作用?我在使用错误的循环吗?还是我尝试使用的方法无法实现我的目标?我还尝试以这种方式写它:

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

,但这也不起作用。

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

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

您需要用简单的while循环替换for...while...循环,以检查您的case_list中是否有任何True

while True not in case_list:
    choose()

这应该起作用!

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

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

您将snapshot的3个字符切片与一个字符进行比较;这些可以从不相等地比较。尝试完整的比赛:

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) )

最新更新