简体   繁体   中英

Why does the break statement not work here?

I just wanna preface this by saying that I'm a beginner and I'm sorry if this is a stupid question/obvious mistake.

I'm making a human vs computer tic tac toe game, and the break statement is not breaking the innermost loop. The problem arises in the very last loop where even if the human wins, the if conditon below it is not executed. It goes on to play the computer's move and THEN declare that the computer has won.

please do inform me if I should change or add something to my question.

Thank You


boardkeys={9:'     ',8:'     ',7:'     ',6:'     ',5:'     ',4:'     ',3:'     ',2:'     ',1:'     '}

def wincon():
    if boardkeys[1]==boardkeys[2]==boardkeys[3]!='     ':
        return True
    elif  boardkeys[4]==boardkeys[5]==boardkeys[6]!='     ':
        return True
    elif  boardkeys[7]==boardkeys[8]==boardkeys[9]!='     ':
        return True
    elif  boardkeys[1]==boardkeys[4]==boardkeys[7]!='     ':
        return True
    elif  boardkeys[2]==boardkeys[5]==boardkeys[8]!='     ':
        return True
    elif  boardkeys[3]==boardkeys[6]==boardkeys[9]!='     ':
        return True
    elif  boardkeys[1]==boardkeys[5]==boardkeys[9]!='     ':
        return True
    elif  boardkeys[3]==boardkeys[5]==boardkeys[7]!='     ':
        return True

hsym="  O  "
csym="  X  "

def ai():
    z=random.randrange(1,10)
    while boardkeys[z]!="     ":
        z=random.randrange(1,10)
    boardkeys[z]=csym

def move():
    no=int(input("enter your move human"))
    if boardkeys[no]=="     ":
        boardkeys[no]=hsym
    else:
        print("invalid move")
        move()
                              
for i in range(10):
    count=0
    move()
    count+=1
    printboard()
    if wincon==True:                     ????
        print("Game Over you won")       ????        
        break                            ????
    elif count==9:
        print("TIED")
        break
    else:
        print()
        print("computer's turn")
        ai()
        printboard()
        if wincon()==True:
            print("Game Over computer won")
            break
        elif count==9:
            print("TIED")
            break

    

Instead of if wincon==True: it should be if wincon()==True: , you're calling a function, not reading a boolean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM