我正在尝试让我的程序加载每个可能的tic-tac-toe板的树,然后当给出随机板输入时,它可以打印出基于树的所有可能的下一步移动。但是,当我尝试这样做时,我的所有节点似乎都返回 $a = array();
array_push($a,array('email' => $this->mail,'votes' => $this->votes));
,但根节点除外。
我的代码现在:
None
这是我当前案例的输出:
import random
def main():
root = createNode(board, None, "X")
setBoard = (" ", " ", " ",
" ", "X", "X",
" ", " ", "O")
nextMoves = find(root, setBoard)
print(nextMoves)
for child in nextMoves.children:
printBoard(child.boardState)
boardCases = set()
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def printBoard(board):
for i in range(3):
print(board[i*3], end="")
print("|", end="")
print(board[i*3+1], end="")
print("|", end="")
print(board[i*3+2], end="")
print("")
if i < 2:
print("-+-+-")
print("~~~~~~~~~~~~")
def checkForWin(board, c):
# all column cases
for i in range(3):
if board[i] == c and board[i+3] == c and board[i+6] == c:
#print(c + " wins!")
return True
#all row cases
for i in range(3):
if board[i*3] == c and board[i*3+1] == c and board[i*3+2] == c:
#print(c + " wins!")
return True
#all across cases
if board[0] == c and board[4] == c and board[8] == c:
#print(c + " wins!")
return True
if board[2] == c and board[4] == c and board[6] == c:
#print(c + " wins!")
return True
#no wins game tie
counter = 0
for i in range(9):
if board[i] == " ":
# no tie found ---> game countinues
return False
else:
counter += 1
if counter == 9:
#print("Tie Game!")
return True
class boardNode:
def __init__(self):
self.boardState = ()
self.children = []
self.winner = ""
def numChildren(self):
return len(self.availableMoves())
def availableMoves(self):
moves = set()
for i in range(9):
if self.boardState[i] == " ":
moves.add(i)
return moves
counter = 0
def createNode(currentBoard, posToFill, c):
global counter
newNode = boardNode()
board = list(currentBoard)
counter +=1
if posToFill != None:
board[int(str(posToFill))] = c
newNode.boardState = tuple(board)
if checkForWin(tuple(board), c) == False:
newNode.winner = None
if c == "X":
for pos in newNode.availableMoves():
newNode.children.append(createNode(newNode.boardState, pos, "O"))
else:
for pos in newNode.availableMoves():
newNode.children.append(createNode(newNode.boardState, pos, "X"))
else:
newNode.winner = c
if newNode.boardState not in boardCases:
boardCases.add(newNode.boardState)
return newNode
def find(node, boardToSearch):
if list(node.boardState) == list(boardToSearch):
return node
else:
for child in node.children:
return find(child, boardToSearch)
if __name__ == "__main__":
main()