minimax算法井字游戏 [英] minimax algorithm tic-tac-toe

查看:142
本文介绍了minimax算法井字游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持为井字游戏实现minimax算法.我每次都会收到相同的错误(nil:NilClass(NoMethodError)的未定义方法'<'),但似乎无法修复.

I am stuck on implementing the minimax algorithm for a tic tac toe game. I keep getting the same error every time (undefined method `<' for nil:NilClass (NoMethodError)) but can't seem to fix it.

我的实现如下:

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

我已经坚持了好几天,所以将不胜感激.

I have been stuck on this for days so any help would be appreciated.

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

推荐答案

我刚刚检查完并调试了它.

I've just been through and debugged this.

事实证明,minimax方法偶尔会返回nil,然后将其推入第94行的moves哈希中,因为它无法将nil与> < 会引发错误,我们无法继续.

It turns out that the minimax method is occasionally returning nil, which is then pushed into the hash of moves on line 94, as it can't compare nil to any number with > or < this throws an error, and we can't proceed.

当结果为nil时,您只需要向后添加零即可,请将第91行更改为:

You just need to add a fallback to 0 when the result is nil, change line 91 to this:

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

您也不需要在循环外定义 score ,因为该变量仅用于将其添加到第94行的哈希中.我之前想念的是score是在 each 循环中再次定义.

You also don't need to define score outside of the loop, as that variable is only used to add it to the hash on line 94. What I'd missed earlier is that score is defined again in the each loop.

这篇关于minimax算法井字游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆