Tic-Tac-Toe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
def newBoard(board): | |
full_board = ['-'] * 9 | |
full_board[:len(board)] = board[:len(board)] | |
return full_board | |
def showBoard(board): | |
full_board = ['-'] * 9 | |
full_board[:len(board)] = board[:len(board)] | |
for i, k in enumerate(full_board): | |
if i % 3 == 2: | |
print(k) | |
else: | |
print(k, end='') | |
print() | |
def selectBoard(board, player, depth): | |
boards = [] | |
if depth == 0: | |
for m in nextMoves(board): | |
next_board = newBoard(board) | |
next_board[m] = player | |
boards.append(next_board) | |
if isWin(next_board, player): | |
showBoard(next_board) | |
else: | |
for m in nextMoves(board): | |
next_board = newBoard(board) | |
next_board[m] = player | |
boards.append(next_board) | |
if not isWin(next_board, player): | |
boards.extend( | |
selectBoard(next_board, 'X' if player == 'O' else 'O', | |
depth - 1)) | |
return boards | |
def isWin(board, player): | |
win = False | |
if player == board[0] == board[1] == board[2]: | |
win = True | |
elif player == board[3] == board[4] == board[5]: | |
win = True | |
elif player == board[6] == board[7] == board[8]: | |
win = True | |
elif player == board[0] == board[3] == board[6]: | |
win = True | |
elif player == board[1] == board[4] == board[7]: | |
win = True | |
elif player == board[2] == board[5] == board[8]: | |
win = True | |
elif player == board[0] == board[4] == board[8]: | |
win = True | |
elif player == board[2] == board[4] == board[6]: | |
win = True | |
return win | |
def nextMoves(board): | |
moves = filter(lambda i: board[i] != 'X' and board[i] != 'O', | |
dict(enumerate(board)).keys()) | |
return list(moves) | |
def main(): | |
board = newBoard([]) | |
boards = selectBoard(board, 'X', 4) | |
for b in boards: | |
#showBoard(b) | |
pass | |
print(len(boards)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment