Connect Four AI实现可用落子从中间向外遍历的方法咨询
四子棋AI落子遍历顺序优化需求
我正在开发四子棋(Connect Four)AI,希望对可用落子位置的遍历顺序按照从中间向外扩散的规则排列。
优化逻辑:由于四子棋规则下,中间位置的落子通常价值更高,这种遍历顺序可以大幅提升alpha-beta剪枝的触发概率,有效优化minimax搜索的运行效率。
具体遍历规则示例
- 奇数长度数组
[1,2,3,4,5],需按3,4,2,5,1的顺序遍历 - 偶数长度数组
[1,2,3,4,5,6],需按4,3,5,2,6,1的顺序遍历
现有四子棋完整实现代码
import os # os.system('cls') 用于清屏 import random import time import sys class ConnectFour: def __init__(self): self.board = [[" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "]] self.numberLine = [1,2,3,4,5,6,7] self.rowCount = 6 self.columnCount = 7 def printBoard(self, column=None, row=None): os.system('cls') # 清空控制台 terminalWidth = os.get_terminal_size().columns terminalHeight = os.get_terminal_size().lines playerToHighlighted = { 'R': '\033[91;44mR\033[0m', 'Y': '\033[93;44mY\033[0m' } print("\n"*round(terminalHeight/2 - (1 + self.columnCount))) highlightedPlayer = '' try: playerHold = self.board[row][column] self.board[row][column] = 'H' highlightedPlayer = playerToHighlighted[playerHold] except: pass print( (((( ((" {} | {} | {} | {} | {} | {} | {} ".format(*self.board[5])).center(terminalWidth)) + '\n' + '\033[94m' + ("---------------------------------------").center(terminalWidth) + '\033[0m' + '\n' + ((" {} | {} | {} | {} | {} | {} | {} ".format(*self.board[4])).center(terminalWidth)) + '\n' + '\033[94m' + ("---------------------------------------").center(terminalWidth) + '\033[0m' + '\n' + ((" {} | {} | {} | {} | {} | {} | {} ".format(*self.board[3])).center(terminalWidth)) + '\n' + '\033[94m' + ("---------------------------------------").center(terminalWidth) + '\033[0m' + '\n' + ((" {} | {} | {} | {} | {} | {} | {} ".format(*self.board[2])).center(terminalWidth)) + '\n' + '\033[94m' + ("---------------------------------------").center(terminalWidth) + '\033[0m' + '\n' + ((" {} | {} | {} | {} | {} | {} | {} ".format(*self.board[1])).center(terminalWidth)) + '\n' + '\033[94m' + ("---------------------------------------").center(terminalWidth) + '\033[0m' + '\n' + ((" {} | {} | {} | {} | {} | {} | {} ".format(*self.board[0])).center(terminalWidth)) + '\n' + '\033[94m' + ("---------------------------------------").center(terminalWidth) + '\033[0m' + '\n' + (((" {} | {} | {} | {} | {} | {} | {} ").format(*self.numberLine)).center(terminalWidth))).replace('Y', '\033[93mY\033[0m')).replace('R', "\033[91mR\033[0m")).replace('|', '\033[94m|\033[0m')).replace('H', highlightedPlayer) ) try: self.board[row][column] = playerHold except: pass def clearBoard(self): self.board = [[" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "], [" ", " ", " ", " ", " ", " "," "]] def makeMove(self, position, player): for row in range(self.rowCount): if self.board[row][position] == " ": self.board[row][position] = player return row def availableMoves(self): # 待优化顺序的可用落子获取逻辑 moves = [] for column in range(self.columnCount): if self.board[self.rowCount - 1][column] == ' ': moves.append(column) return moves def removeMove(self, row, column): self.board[row][column] = " " def checkWin(self): for player in ('R', 'Y'): for column in range(self.columnCount - 3): # 检查水平方向获胜 for row in range(self.rowCount): if self.board[row][column] == player and self.board[row][column+1] == player and self.board[row][column+2] == player and self.board[row][column+3] == player: return player for column in range(self.columnCount): # 检查垂直方向获胜 for row in range(self.rowCount - 3): if self.board[row][column] == player and self.board[row+1][column] == player and self.board[row+2][column] == player and self.board[row+3][column] == player: return player for column in range(self.columnCount- 3): # 检查正斜率对角线获胜 for row in range(self.rowCount - 3): if self.board[row][column] == player and self.board[row+1][column+1] == player and self.board[row+2][column+2] == player and self.board[row+3][column+3] == player: return player for column in range(self.columnCount-3): # 检查负斜率对角线获胜 for row in range(3, self.rowCount): if self.board[row][column] == player and self.board[row-1][column+1] == player and self.board[row-2][column+2] == player and self.board[row-3][column+3] == player: return player def whoWon(self): if self.checkWin() == 'R': return "红方" elif self.checkWin() == 'Y': return "黄方" elif self.checkGameOver() == True: return "平局" def checkGameOver(self): if self.checkWin() != None: return True for column in range(self.columnCount): if self.board[self.rowCount - 1][column] == " ": return False return True def getMoveCount(self, player): moveCount = 0 for column in range(self.columnCount): for row in range(self.rowCount): if self.board[row][column] == player: moveCount += 1 return moveCount def minimax(self, node, depth, alpha, beta, player): if depth == 0 or node.checkGameOver(): if node.checkWin() == 'R': return -(22 - self.getMoveCount('R')) elif node.checkWin() == 'Y': return 22 - self.getMoveCount('Y') else: return 0 if player == 'Y': maxValue = -(sys.maxsize) for move in node.availableMoves(): moveRow = node.makeMove(move, player) moveValue = self.minimax(node, depth-1, alpha, beta, changePlayer(player)) node.removeMove(moveRow, move) maxValue = max(maxValue, moveValue) alpha = max(alpha, moveValue) if beta <= alpha: break return maxValue if player == 'R': minValue = sys.maxsize for move in node.availableMoves(): moveRow = node.makeMove(move, player) moveValue = self.minimax(node, depth-1, alpha, beta, changePlayer(player)) node.removeMove(moveRow, move) minValue = min(minValue, moveValue) beta = min(beta, moveValue) if beta <= alpha: break return minValue def changePlayer(player): if player == 'R': return 'Y' else: return 'R' def makeBestMove(board, depth, player): neutralValue = 0 choices = [] bestLossingMoveValue = -(sys.maxsize) for move in board.availableMoves(): moveRow = board.makeMove(move, player) moveValue = board.minimax(board, depth-1, -(sys.maxsize), sys.maxsize, changePlayer(player)) board.removeMove(moveRow, move) print(moveValue) if moveValue > neutralValue: choices = [move] break elif moveValue == neutralValue: choices.append(move) elif moveValue > bestLossingMoveValue: bestLossingMove = move if len(choices) > 0: return random.choice(choices), choices elif bestLossingMove != None: return bestLossingMove, [False] else: return random.choice(board.availableMoves()), [] def askPlayAgain(): terminalWidth = os.get_terminal_size().columns print("是否要再来一局?".center(terminalWidth)) playAgain = input(' ' * round(terminalWidth/2 - 8) + "输入y/n: ") if playAgain == 'y': game.clearBoard() game.printBoard() setupGame() elif playAgain == 'n': exit() else: game.printBoard() print("输入错误,请重试!".center(terminalWidth)) askPlayAgain() playerToColor = { 'R': '\033[91m红方\033[0m', 'Y': '\033[93m黄方\033[0m' } def askPlayerMove(player): terminalWidth = os.get_terminal_size().columns print(("你操控的是" + playerToColor[player] + ":请输入1-7之间的列号落子").center(terminalWidth + 8)) move = input(" " * round(terminalWidth/2 - 9) + "输入落子位置: ") try: move = int(move) - 1 except: game.printBoard() print("输入错误,请重试!".center(terminalWidth)) return askPlayerMove(player) if move >= 0 and move <= game.columnCount - 1: row = game.makeMove(move, player) return [move, row] else: game.printBoard() print("输入错误,请重试!".center(terminalWidth)) return askPlayerMove(player) def askDepth(): terminalWidth = os.get_terminal_size().columns print("请设置AI的搜索深度:").center(terminalWidth) depth = input(" " * round(terminalWidth/2 - 17) + "输入搜索深度(推荐值9): ") try: depth = int(depth) return depth except: game.printBoard() print("输入错误,请重试!").center(terminalWidth) return askDepth() def setupGame(): terminalWidth = os.get_terminal_size().columns print("请选择对战模式:人机对战/双人玩家对战").center(terminalWidth) gameMode = input(" " * round(terminalWidth/2 - 8) + "输入c/p选择模式(c=人机,p=双人): ") if gameMode == 'p': startGame(gameMode) elif gameMode == 'c': game.printBoard() depth = askDepth() startGame(gameMode, depth) else: game.printBoard() print("输入错误,请重试!").center(terminalWidth) setupGame() def startGame(gameMode, depth=None): game.printBoard() while game.checkGameOver() == False: movePosition = askPlayerMove('R') game.printBoard(movePosition[0], movePosition[1]) if game.checkGameOver() == True: break if gameMode == 'c': terminalWidth = os.get_terminal_size().columns print("AI正在计算最优落子...").center(terminalWidth) computerMove = makeBestMove(game, depth, 'Y') movePosition[1] = game.makeMove(computerMove[0], 'Y') movePosition[0] = computerMove[0] computerChoices = computerMove[1] elif gameMode == 'p': movePosition = askPlayerMove('Y') game.printBoard(movePosition[0], movePosition[1]) if gameMode == 'c': print(("AI的等效最优落子列表:" + str(computerChoices)).center(terminalWidth)) terminalWidth = os.get_terminal_size().columns game.printBoard() print(("对局结束," + game.whoWon() + "获胜").center(terminalWidth)) askPlayAgain() if __name__ == '__main__': game = ConnectFour() game.printBoard() setupGame()
内容的提问来源于stack exchange,提问作者TNT_7
相关产品推荐
相关产品推荐

