调试堆栈级别太深错误 - Ruby

Debugging a stack level too deep error - Ruby

我正在构建一个井字游戏,用户可以在其中玩计算机,或者计算机可以互相玩。在构建 AI 时,我 运行 出现以下错误。我该如何调试呢?我知道这与某处的循环有关,但我找不到它。

ttt-with-ai-project-cb-000/lib/players/computer.rb:13:in `each': stack level too deep (SystemStackError)
        from ttt-with-ai-project-cb-000/lib/players/computer.rb:13:in `detect'
        from ttt-with-ai-project-cb-000/lib/players/computer.rb:13:in `check_move'
        from ttt-with-ai-project-cb-000/lib/players/computer.rb:8:in `move'
        from ttt-with-ai-project-cb-000/lib/game.rb:61:in `wargame_turn'
        from ttt-with-ai-project-cb-000/lib/game.rb:64:in `wargame_turn'
        from ttt-with-ai-project-cb-000/lib/game.rb:64:in `wargame_turn'
        from ttt-with-ai-project-cb-000/lib/game.rb:64:in `wargame_turn'
        from ttt-with-ai-project-cb-000/lib/game.rb:64:in `wargame_turn'
         ... 11900 levels...
        from bin/tictactoe:37:in `block in run_game'
        from bin/tictactoe:35:in `times'
        from bin/tictactoe:35:in `run_game'
        from bin/tictactoe:79:in `<main>'


违规方法

lib/players/computer.rb

def move(board)
    check_move(board)
end

def check_move(board)
    win_combo = Game::WIN_COMBINATIONS.detect do |indices|
    board.cells[indices[0]] == token && board.cells[indices[1]] == token || board.cells[indices[1]] == token && board.cells[indices[2]] == token || board.cells[indices[0]] == token && board.cells[indices[2]] == token
    end

    win_combo.detect {|index| board.cells[index] == " "}.join if win_combo
end


lib/game.rb

def wargame_turn
    input = current_player.move(board)

    if !board.valid_move?(input)
        wargame_turn
    else
        board.update(input, current_player)
    end
end


bin/tictactoe 在#run_game:

中调用以下块中的方法
100.times do 
    game = Game.new(Players::Computer.new("X"), player_2 = Players::Computer.new("O"))
    game.wargames
    if game.winner == "X"
        x_wins += 1
    elsif game.winner == "O"
        x_wins += 1
    elsif game.draw?
        draws += 1
    end
end

您可以使用 ruby Tracer class:

ruby -r tracer your_main_script.rb

此外,您可以查看您的代码,看看循环可能发生的位置:

def wargame_turn

  input = current_player.move(board)

  if !board.valid_move?(input)

    wargame_turn #### HERE'S A POTENTIAL INFINITE LOOP

所以问题的核心似乎在:

if !board.valid_move?(input)

这可能是一个好的开始。