Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from array import array
- import numpy as np
- boardState = array('i', [1, 0, 0, 0, -1, 0, 0, 0, 0])
- boardDisp = array('u', [' '] * 9)
- minimaxPlayer = 1
- def printBoard(board) :
- i = 0
- while i < len(board):
- if board[i] == 1 :
- boardDisp[i] = 'X'
- elif board[i] == -1 :
- boardDisp[i] = 'O'
- else :
- boardDisp[i] = ' '
- i += 1
- print('-----')
- print(boardDisp[0], boardDisp[1], boardDisp[2])
- print(boardDisp[3], boardDisp[4], boardDisp[5])
- print(boardDisp[6], boardDisp[7], boardDisp[8])
- print('-----')
- def rowColumn(row, column) : # 0 indexed 0-2
- i = (3 * row) + column
- return i
- def playerInput(player) :
- row = int(input('Row? '))
- column = int(input('Column? '))
- if boardState[rowColumn(row, column)] == 0 :
- boardState[rowColumn(row, column)] = player
- printBoard(boardState)
- else:
- if checkWin(boardState) == 0 :
- printBoard(boardState)
- print('Square already filled. Try again')
- playerInput(player)
- else :
- return
- def checkWin(board1) :
- board = np.array(board1).reshape(3, 3)
- if sum(np.abs(boardState)) == 9 :
- return 0
- for i in range(3) :
- if sum(board[i]) == 3 or sum(board[:, i]) == 3 :
- return 1
- elif sum(board[i]) == -3 or sum(board[:, i]) == -3 :
- return -1
- if sum(board.diagonal()) == 3 or sum(np.fliplr(board).diagonal()) == 3 :
- return 1
- elif sum(board.diagonal()) == -3 or sum(np.fliplr(board).diagonal()) == -3 :
- return -1
- else :
- return 2
- def moveSearch(board, player) :
- #printBoard(board)
- if abs(checkWin(board)) == 1 :
- return checkWin(board) * player * -1
- elif checkWin(board) == 0:
- return 0
- elif checkWin(board) == 2 :
- moveList = array('i', [])
- i = 0
- while i < 9 :
- if board[i] == 0 :
- moveList.append(i)
- i += 1
- j = 0
- valueList = array('f', [0] * len(moveList))
- while j < len(moveList) :
- board[moveList[j]] = player
- valueList[j] = moveSearch(board, -1 * player)
- board[moveList[j]] = 0
- j += 1
- return max(valueList) * -1
- def topLevelSearch(board, player) :
- printBoard(board)
- if abs(checkWin(board)) == 1 :
- return
- elif checkWin(board) == 0:
- return
- elif checkWin(board) == 2 :
- moveList = array('i', [])
- i = 0
- while i < 9 :
- if board[i] == 0 :
- moveList.append(i)
- i += 1
- j = 0
- valueList = array('f', [0] * len(moveList))
- while j < len(moveList) :
- board[moveList[j]] = player
- valueList[j] = moveSearch(board, -1 * player)
- board[moveList[j]] = 0
- j += 1
- bestMove = moveList[valueList.index(max(valueList))]
- return bestMove
- minimaxMove = topLevelSearch(boardState, minimaxPlayer)
- boardState[minimaxMove] = minimaxPlayer
- printBoard(boardState)
- print(boardState)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement