首页 > 解决方案 > 模拟计算机的移动并用分数更新玩家的回合

问题描述

我用 JavaScript 写了一个井字游戏。我想模拟电脑的回合,也想更新玩家的分数。

我该如何编写这段代码?我编写了一些适用于播放器 X 和 O 的代码,但它们没有得到更新。我想看看轮到哪个玩家以及每个玩家的得分

const gameState = {
    currentPlayer: 'x',
    players: ['x', 'o'],
    board: [
        [null, null, null],
        [null, null, null],
        [null, null, null]
    ]
}
var turn = 1;
var P1Score = 0;
var p2Score = 0;

function checkWinner(player) {
    if ($(".row-1 .cell." + player).length === 3 ||
        $(".row-2 .cell." + player).length === 3 ||
        $(".row-3 .cell." + player).length === 3 ||
        $(".col1." + player).length === 3 ||
        $(".col2." + player).length === 3 ||
        $(".col3." + player).length === 3 ||
        ($("#1").hasClass(player) &&
            $("#5").hasClass(player) &&
            $("#9").hasClass(player)) ||
        ($("#3").hasClass(player) &&
            $("#5").hasClass(player) &&
            $("#7").hasClass(player))) {
        $(".cell ").empty();
        $(".cell").removeClass("x");
        $(".cell").removeClass("o");
        $(".cell").css('background', 'blue')
        return true;
    }
}

$('.cell').click(function() {
    
    if (gameState.currentPlayer == "x" &&   !$(this).hasClass("o")) {
        $(this).text("x")
        $(this).addClass("x")
        $(".x").css('background', 'gold')

        if (checkWinner("x")) {

            alert(`${gameState.currentPlayer}is the winner!.Start a new game`)

        } else checkTie()

    } else if (!$(this).hasClass("x")) {
        $(this).text("o")
        $(this).addClass("o")

        if (checkWinner("o")) {

            alert(`${gameState.currentPlayer}is the winner!. Start a new game`)

        } else checkTie()
    }

    changePlayer();
});

function changePlayer(){
  if( gameState.currentPlaye == 'x') {
    gameState.currentPlayer = 'o'
  } else {
    gameState.currentPlayer = 'x'
  };
};

function checkTie() {
    if ($(".x").length + $(".o").length === 9) {
        $(".cell ").empty();
        $(".x").removeClass("x");
        $(".o").removeClass("o");
        alert("Its a tie")

    };
};

$('.restart').click(function() {
    $(".cell ").empty();
    $(".cell").removeClass("x");
    $(".cell").removeClass("o");
    $(".cell").css('background', 'blue')
});

标签: javascript

解决方案


推荐阅读