gpt4 book ai didi

python - 检查 TicTacToe 获胜条件的有效方法//编辑 : How to check for tie?

转载 作者:行者123 更新时间:2023-12-01 05:02:05 25 4
gpt4 key购买 nike

所以我用 Python 制作了一个 TicTacToe 程序作为我的第一个小项目(使用 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

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

编辑:刚刚注意到我的程序中有一个错误。我没有任何领带检查,陷入领带情况会让您陷入困境 - 我如何检查领带?我不知道如何才能做到这一点。

最佳答案

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

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)

附:你不需要那些反斜杠。在括号内足以让 Python 知道表达式继续。

关于python - 检查 TicTacToe 获胜条件的有效方法//编辑 : How to check for tie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25876814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com