Python tic-tac-toe

时间:2015-10-21 15:11:18

标签: python algorithm function tic-tac-toe

python2中的tac-toe游戏,但是当程序遇到3-Xs或3-Os时我无法停止游戏 这是我的代码:

a=[]
for i in range(0,10):
    a.append(" ")
def table():
    print "  " + a[1]+ "  |  " +a[2]+ "  |  " +a[3] +"  "
    print "-----------------"
    print "  " + a[4]+ "  |  " +a[5]+ "  |  " +a[6] +"  "
    print "-----------------"
    print "  " + a[7]+ "  |  " +a[8]+ "  |  " +a[9] +"  "



table()
#x = None
def play():
    global x
    for i in range(1,10):
        x= None
        if (i%2==1):
            while ((x>9 or x<0) ):
                x=int(raw_input("Player1, it's your turn : "))
            while ((a[x]=="O" or a[x]=="X")):
                x=int(raw_input("Player1, it's your turn : "))
            a[x]='X'
            table()

        if (i%2==0):
            while ((x>9 or x<0) ):
                x=int(raw_input("Player2, it's your turn : "))
            while ((a[x]=="O" or a[x]=="X")):
                x=int(raw_input("Player2, it's your turn : "))
            a[x]='O'
            table()

            if win() or win2():
                return



def win():
    if (a[1]=="X" and a[2]=="X" and a[3]=="X") or \
     (a[4]=="X" and a[5]=="X" and a[6]=="X") or \
     (a[7]=="X" and a[8]=="X" and a[9]=="X") or \
     (a[1]=="X" and a[4]=="X" and a[7]=="X") or \
     (a[2]=="X" and a[5]=="X" and a[8]=="X") or \
     (a[3]=="X" and a[6]=="X" and a[9]=="X") or \
     (a[1]=="X" and a[5]=="X" and a[9]=="X") or \
     (a[3]=="X" and a[5]=="X" and a[7]=="X") : print "PLAYER1 WON, Congratulations !!!"

#######


def win2():
    if (a[1]=="O" and a[2]=="O" and a[3]=="O") or \
     (a[4]=="O" and a[5]=="O" and a[6]=="O") or \
     (a[7]=="O" and a[8]=="O" and a[9]=="O") or \
     (a[1]=="O" and a[4]=="O" and a[7]=="O") or \
     (a[2]=="O" and a[5]=="O" and a[8]=="O") or \
     (a[3]=="O" and a[6]=="O" and a[9]=="O") or \
     (a[1]=="O" and a[5]=="O" and a[9]=="O") or \
     (a[3]=="O" and a[5]=="O" and a[7]=="O"): print "PLAYER2 WON, Congratulations !!!"



    #else: print "Egalitate !!!"



def egal():
    if (not win() and not win2() ):
        print "Egalitate !" 





play()
#win()
#egal()

如你所见,我编码:

if win() or win2():
    return

不幸的是,当它遇到任何一个TRUE时,它不会退出程序。

1 个答案:

答案 0 :(得分:1)

win应返回一个布尔值,表示玩家是否赢了

def win():
    return (a[1]=="X" and a[2]=="X" and a[3]=="X") or \
     (a[4]=="X" and a[5]=="X" and a[6]=="X") or \
     (a[7]=="X" and a[8]=="X" and a[9]=="X") or \
     (a[1]=="X" and a[4]=="X" and a[7]=="X") or \
     (a[2]=="X" and a[5]=="X" and a[8]=="X") or \
     (a[3]=="X" and a[6]=="X" and a[9]=="X") or \
     (a[1]=="X" and a[5]=="X" and a[9]=="X") or \
     (a[3]=="X" and a[5]=="X" and a[7]=="X")

play中,您拨打win,如果它返回TRUE,则printreturn

if win():
    print "PLAYER1 WON, Congratulations !!!"
    return

您当然可以对win2执行相同操作。