Skip to content

Instantly share code, notes, and snippets.

@lyshie
Created May 7, 2021 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyshie/aa09d6c2f87e97415a2e8e499295d583 to your computer and use it in GitHub Desktop.
Save lyshie/aa09d6c2f87e97415a2e8e499295d583 to your computer and use it in GitHub Desktop.
Tic-Tac-Toe
#!/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