检查TicTacToe获胜条件的有效方法//编辑:如何检查平局?

2024-10-03 13:17:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

编辑:刚刚注意到我的程序有个错误。我没有任何平局检查,进入一个平局将导致你卡住-我如何检查平局?我不知道我怎么能做到。在


Tags: or程序forinputreturnifos条件
1条回答
网友
1楼 · 发布于 2024-10-03 13:17:27

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

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

然后在它们之间循环,例如

^{pr2}$

(您需要同时对X和O运行这个,即添加一个外部循环并使用其变量而不是内部的文本X/O)

另外,你不需要那些反斜杠。在圆括号内就足以让Python知道表达式继续。在

相关问题 更多 >