【发布时间】:2020-12-01 10:42:50
【问题描述】:
我一直坚持为井字游戏实现极小极大算法。我每次都遇到同样的错误(未定义的方法 `
我的极小极大实现如下:
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 = []
score = nil
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'
moves.each do |hsh|
hsh.each do |move, score|
if score > best_score
best_move = move
best_score = score
end
end
end
else
moves.each do |hsh|
hsh.each do |move, score|
if score < best_score
best_move = move
best_score = score
end
end
end
end
best_move
end
当递归调用 minimax 时,它有时会返回 nil,然后将其附加到 move 散列中,其中 move 然后附加到 moves 数组中。这会导致< 运算符引发上述异常。我不知道为什么nil 会被退回。
我只能假设我的逻辑有缺陷。在尝试了可能的电路板状态后,我的电路板可能没有正确重置,但老实说,我不知道如何继续。我尝试了多种实现,但总是得到相同的错误。
我已经坚持了一个多星期,非常感谢一些帮助。
【问题讨论】:
-
这能回答你的问题吗? minimax algorithm tic-tac-toe
-
不 :(。不幸的是它没有。
-
“我不知道为什么返回 nil” – 当
moves为空时,即[],best_move保持nil然后变为返回值。 -
我不明白
minimax是如何工作的,但是如果您需要一个数值,您可以将方法的最后一行更改为best_move || 0以提供默认值(将0更改为任何值有道理) -
没关系@Stefan。我不知道 Ruby 但 MiniMax 并尝试解决问题 ;)
标签: ruby recursion tic-tac-toe minimax