如果这是重新发布的话我提前道歉,但我已经阅读了有关该主题的其他帖子,我仍然无法弄清楚该怎么做。我试图在ruby tic tac toe游戏中实现Negamax,我在第55行遇到了堆栈溢出错误。我在Negamax上阅读了很多帖子和文章,我仍然无法让它工作。
这个文件还不是一个更大的程序的一部分,我只是想通过一个董事会,看看它是否会采取行动。
class Negamax
attr_accessor :board, :mark, :depth, :winning_routes
def initialize
@board = ["X","2","3","4","5","6","7","8","9"]
@mark = "O"
@depth = 1
@winning_routes = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
end
def negamax(board, mark, depth)
if winner?(mark) || isboardfull?(board)
return game_result(mark)
else
max = -1.0/0
mark == "O" ? opponent = "X" : "O"
available_moves.each do |space|
board[space] = mark
score = -negamax(board, opponent, depth + 1)
board[space] = "#{space + 1}"
if score > max
max = score
best_move = space if depth == 1
board[best_move] = mark
end
end
return max
end
end
def available_moves()
board.each_index.select { |s| board[s] != "X" && board[s] != "O"}
end
def isboardfull?(board)
boardtos = board.join(",")
boardtos =~ /\d/ ? false : true
end
def game_result(mark)
if winner?(mark)
return 1
elsif winner?(mark == "O" ? "X" : "O")
return -1
else
return 0
end
end
def winner?(mark)
result = false
marker = mark
winning_routes.each do |group|
if board[group[0]] == marker && board[group[1]] == marker && board[group[2]] == marker
result = true
end
end
result
end
end
game = Negamax.new()
game.negamax(game.board, game.mark, game.depth)
print game.board