不可能的井字游戏 Javascript

Bla*_*ine -2 javascript tic-tac-toe angularjs

我正在开发一个基本的 Javascript Tic Tac Toe 游戏,让用户与计算机对战。这个游戏的要求之一是用户永远不能打败电脑,他们所能做的就是平局。我在弄清楚这方面的逻辑时遇到了麻烦,而且我还没有看到任何我能理解的关于如何实现这一点的例子。现在计算机只是选择一个随机位置来决定轮到它。如果这个随机点是左上角(randomChoice==0)或右下角(randomChoice ==9),它会将其更改为旁边的框。我已经在下面发布了代码,任何关于此的提示都会有所帮助。这也是我目前在 CodePen 上所有代码的链接。http://codepen.io/Android162010/pen/LGZXQa

function playRandom() {    


    randomChoice = Math.round(Math.random() * 10);

    if (randomChoice == 0) {
        randomChoice = 1;
    }
    if (randomChoice == 10) {
        randomChoice = 9;
    }


    if ($('#' + randomChoice).hasClass('hoverable')) {
        makeTic('#' + randomChoice, false);
    }
    else {
        playRandom();
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以使用 minimax 算法创建用于玩 Tic Tac Toe 的 AI。

这是一篇关于与 Tic Tac Toe 一起使用的 minimax 的文章:http : //neverstopbuilding.com/minimax

这个想法是,不是随机选择动作,而是展望游戏未来可能的状态,并根据它们的好坏程度对它们进行排名。作者提出了一个系统,其中获胜的节点被分配了 +10 的值,而失败的节点被分配了 -10。

# @player is the turn taking player
def score(game)
    if game.win?(@player)
        return 10
    elsif game.win?(@opponent)
        return -10
    else
        return 0
    end
end
Run Code Online (Sandbox Code Playgroud)

一旦你有了一个根据未来状态对你的好坏程度对未来状态进行排名的系统,你就可以制定一个算法来选择最佳状态。下面是作者对该算法的通俗解释:

假设 X 是“轮流玩家”,对算法的描述如下所示:

  • 如果游戏结束,从 X 的角度返回分数。
  • 否则获取每个可能移动的新游戏状态列表
  • 创建分数列表
  • 对于这些状态中的每一个,将该状态的极小极大结果添加到分数列表中
  • 如果轮到 X,则返回分数列表中的最高分数
  • 如果轮到 O,则返回分数列表中的最低分数

最后,这是作者的解决方案

def minimax(game, depth)
    return score(game) if game.over?
    depth += 1
    scores = [] # an array of scores
    moves = []  # an array of moves

# Populate the scores array, recursing as needed
game.get_available_moves.each do |move|
    possible_game = game.get_new_state(move)
    scores.push minimax(possible_game, depth)
    moves.push move
end

# Do the min or the max calculation
if game.active_turn == @player
    # This is the max calculation
    max_score_index = scores.each_with_index.max[1]
    @choice = moves[max_score_index]
    return scores[max_score_index]
else
    # This is the min calculation
    min_score_index = scores.each_with_index.min[1]
        @choice = moves[min_score_index]
        return scores[min_score_index]
    end
end
Run Code Online (Sandbox Code Playgroud)

  • [“始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。”](http://stackoverflow.com/help/how-to-answer) 您能否总结或引用网站的重要部分? (3认同)