【问题标题】:minimax algorithm tic-tac-toe极小极大算法井字游戏
【发布时间】:2020-11-28 20:17:08
【问题描述】:

我一直坚持为井字游戏实现极小极大算法。我每次都遇到同样的错误(未定义的方法 `

我的实现如下:

def minimax(current_board, current_player)
  if user_won?(current_board)
    return -10
  elsif computer_won?(current_board)
    return 10
  elsif tie?(current_board)
    return 0
  end

  available_squares = empty_squares(current_board)
  moves = []

  available_squares.each do |available_square|
    move = {}
    current_board[available_square] = COMPUTER_MARKER if current_player == 'computer'
    current_board[available_square] = PLAYER_MARKER if current_player == 'player'
    score = minimax(current_board, alternate_player(current_player))
    current_board[available_square] = INITIAL_MARKER
    move[available_square] = score
    moves.push(move)
  end

  best_move = nil
  best_score = current_player == 'computer' ? -Float::INFINITY : Float:: INFINITY

  if current_player == 'computer'
    for hsh in moves
      hsh.each do |move, score|
        if score > best_score
          best_move = move
          best_score = score
        end
      end
    end
  else
    for hsh in moves 
      hsh.each do |move, score|
        if score < best_score
          best_move = move
          best_score = score
        end
      end
    end
  end
  best_move
end

我已经坚持了好几天,所以任何帮助都将不胜感激。

这是我的其余代码:https://github.com/YBirader/launch_school/blob/master/RB101/lesson_6/ttt.rb

【问题讨论】:

  • 看起来 score 是在一个循环中定义的,available_squares.each - 所以如果 available_squares 为空,则该代码将永远不会运行,并且将不会定义 score。这将导致此错误。
  • 分数仅在块内使用。它被添加到移动哈希中,然后破坏性地附加到移动数组中,因此这不应该是问题。如果有帮助,我已经添加了我的其余代码。

标签: ruby algorithm tic-tac-toe minimax


【解决方案1】:

变量score 必须在循环之外定义。然后一行

if score > best_score

会起作用的。

【讨论】:

  • 我试过了,但还是不行。我犯了同样的错误。此外,每个块都在访问移动哈希元素的分数键,所以我不需要在 for 循环之前定义分数。
  • 要测试这是否是问题所在,请尝试在“available_squares.each”之前添加“score = 0”。
【解决方案2】:

我刚刚完成并调试了这个。

事实证明,minimax 方法偶尔会返回 nil,然后将其推入第 94 行的移动哈希中,因为它无法将 nil 与 &gt;&lt; 的任何数字进行比较,这会引发错误,我们无法继续。

你只需要在结果为 nil 时添加一个回退到 0,将第 91 行更改为:

minimax(current_board, alternate_player(current_player)) || 0

您也不需要在循环之外定义 score,因为该变量仅用于将其添加到第 94 行的哈希中。我之前错过的是在 @ 中再次定义了分数987654325@循环。

【讨论】:

  • 但是如果 minimax 返回 0,这是一个错误?
  • 是的。尽管它消除了错误,但 minimax 函数不再起作用,即逻辑现在是错误的。
猜你喜欢
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
相关资源
最近更新 更多