检查TicTacToe胜利条件的有效方法//编辑:如何检查领带?

时间:2014-09-16 19:22:27

标签: python tic-tac-toe

所以我做了一个TicTacToe程序作为我在Python中的第一个小项目(使用3.4)。

它到目前为止有效,但我想知道是否可以简化获胜条件检查

import os
clear = lambda: os.system('cls')



def playerChange(player):  #Function for easily swapping out players
    if player == "X":
        return "O"
    else:
        return "X"

player = "X"  #Setting initial player
tttfield = ["1","2","3","4","5","6","7","8","9"] #setting up tictactoe field
clear()
while True:

    print("", tttfield[0], "|", tttfield[1], "|", tttfield[2], "\n",
          "---------", "\n",
          tttfield[3], "|", tttfield[4], "|", tttfield[5], "\n",
          "---------", "\n",
          tttfield[6], "|", tttfield[7], "|", tttfield[8], "\n")

    choice = 0
    choice = input("\n%s, choose a slot: " % player)
    if choice in tttfield:
        tttfield[int(choice)-1] = player #marks space
        player = playerChange(player) #changes player
    else:
        input("Not a valid number! Choose again!")
    clear()

    #check for win condition
    if ((tttfield[0]==tttfield[1]==tttfield[2]) or\
        (tttfield[3]==tttfield[4]==tttfield[5]) or\
        (tttfield[6]==tttfield[7]==tttfield[8]) or\
        (tttfield[0]==tttfield[3]==tttfield[6]) or\
        (tttfield[1]==tttfield[4]==tttfield[7]) or\
        (tttfield[2]==tttfield[5]==tttfield[8]) or\
        (tttfield[0]==tttfield[4]==tttfield[8]) or\
        (tttfield[6]==tttfield[4]==tttfield[2])) :
        clear()
        input("\n\n  %s wins!" % playerChange(player))
        break

由于所有检查,胜利条件检查看起来相当笨拙。有没有办法压缩它?

编辑:刚刚注意到我程序中的一个错误。我没有任何领带检查,并且遇到平局会让你陷入困境 - 我该如何检查领带?我不知道我怎么能这样做。

1 个答案:

答案 0 :(得分:2)

一种常见的方法是将获胜状态存储在紧凑的数据结构中,例如

winners = [[0, 1, 2], [3, 4, 5] ...]

然后循环遍历它们,例如

for squares in winners:
    if all(tttfield[square]=='x' for square in squares):
        print "X wins!"

(你想为X和O运行它,即添加一个外部循环并使用其变量而不是文字X / O)

P.S。你不需要那些反斜杠。在括号内,足以让Python知道表达式继续存在。