gpt4 book ai didi

ruby - Minimax 算法 Ruby Tic Tac Toe

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:50 25 4
gpt4 key购买 nike

我正在使用 minimax 算法编写无与伦比的井字游戏。出于某种原因,我的分数散列在出现循环时失去了它的值(value)。如果它正在发生,那么我一定做错了我无法捕捉到的事情。我是编码新手。需要帮助!!!

mark是当前玩家的标记

mark1和mark2分别是player1和player2的两个标记

spots是棋盘上的空白点

require_relative 'board'

class ComputerPlayer
attr_reader :board

def initialize
@board = Board.new
@optimal_moves = [0, 2, 4, 6, 8]
end

def get_position(name, spots, mark, mark1, mark2)
position = nil
other_mark = nil
mark == mark1 ? other_mark = mark2 : other_mark = mark1
if spots.length == 9
position = @optimal_moves.sample.to_i
else
position = best_move(spots, mark, other_mark)
end
print "Enter your move #{name}: #{position}\n"
position
end

def best_move(spots, mark, other_mark, depth = 0, scores = {})
return 1 if board.winner == mark
return 0 if board.draw?
return -1 if board.winner == other_mark

spots.each do |move|
board.place_mark(move, mark)
scores[move] = best_move(spots[1..-1], mark, other_mark, depth += 1, {})
board.reset_position(move)
end

# it does not keep the value of scores. scores here is {}
return scores.max_by { |key, value| value }[0] if depth == 0
return scores.max_by { |key, value| value }[1] if depth > 0
return scores.min_by { |key, value| value }[1] if depth < 0
end
end

最佳答案

看起来您每次都将空散列传回 best_move。您可能想要做的是在每次重复时传递分数,以构建一个包含移动和分数的对象。

scores[move] = best_move(spots[1..-1], mark, other_mark, depth += 1, scores)

关于ruby - Minimax 算法 Ruby Tic Tac Toe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52940424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com