Ruby 的 Minimax 函数

问题描述 投票:0回答:0

我请 ChatGPT(我最好的编程错误朋友)帮助制作一个功能,使井字游戏的最佳动作成为可能。我在 Youtube 上看过一些解释最佳井字棋动作的视频,我想用正确的最佳动作对所有这些可能性进行硬编码。当我询问 ChatGPT 时,它让我彻底改变了我心爱的井字棋程序。 ChatGPT 向我介绍了 Minimax。在我下面的程序中有没有一种方法可以简单地添加一个 minimax 函数(返回最佳移动索引)并用它替换我的随机移动生成器?另外,请不要添加任何我不理解的函数(除了 minimax 之外)或奇怪的丑陋语句。

game = [0, 1, 2, 3, 4, 5, 6, 7, 8]
done = Array.new(9, false)

winning_arrangements_player = [
    [0, 1, 2], [3, 4, 5], [6, 7, 8],
    [0, 3, 6], [1, 4, 7], [2, 5, 8],
    [0, 4, 8], [2, 4, 6]
]

winning_arrangements_computer = [
    [0, 1, 2], [3, 4, 5], [6, 7, 8],
    [0, 3, 6], [1, 4, 7], [2, 5, 8],
    [0, 4, 8], [2, 4, 6]
]

gameplay = true

while gameplay
    input = gets.to_i
    if input < 0 || input > 8
        puts "Put a number from 0 to 8!"
        next
    end
    if(!done[input])
        game[input] = "o"
        done[input] = true
    else
        puts "That spot is filled!"
        next
    end

    if winning_arrangements_player.any? { |arr| arr.all? { |pos| game[pos] == "o" } }
        puts "Player wins!"
        gameplay = false
        break
    end

    if !done.include?(false)
        puts "game over!"
        gameplay = false
        break
    end

    while true
        cmove = rand 9
        if done[cmove] == true
            next
        else
            game[cmove] = "x"
            done[cmove] = true
            if winning_arrangements_computer.any? { |arr| arr.all? { |pos| game[pos] == "x" } }
                puts "Computer wins!"
                gameplay = false
                break
            end
            puts "The computer chose #{cmove}."
            break
        end
    end

    puts "#{game[0]}|#{game[1]}|#{game[2]}"
    puts "#{game[3]}|#{game[4]}|#{game[5]}"
    puts "#{game[6]}|#{game[7]}|#{game[8]}"
end

我试过了:

  • 询问聊天GPT
  • 删除 ChatGPT 所有我没有要求的丑陋代码

我预计:

  • 一个完全工作的基于 minimax 的 ruby tic-tac-toe 对抗计算机程序
ruby artificial-intelligence tic-tac-toe minimax
© www.soinside.com 2019 - 2024. All rights reserved.