TicTacToe中的重置和绑定功能问题

时间:2017-08-01 20:08:42

标签: javascript jquery html

我构建了一个简单的tic tac toe游戏,并且运行良好。我想实现一个重置按钮和一个平局功能,但我似乎无法将我的代码包裹起来。

我理解使用location.reload重置很简单,但我不知道在jquery中将它包装在哪里。

我很遗憾在哪里返回我的职能领带。 这是我的代码

<div id = "gameboard">
  <div class= "row">
    <div class = "square bottom right sq1"></div>
    <div class = "square bottom right sq2"></div>
    <div class = "square bottom sq3"></div>
  </div>
  <div class= "row">
    <div class = "square bottom right sq4"></div>
    <div class = "square bottom right sq5"></div>
    <div class = "square bottom sq6"></div>
  </div>
  <div class= "row">
    <div class = "square right sq7"></div>
    <div class = "square right sq8"></div>
    <div class = "square sq9"></div>
  </div>
  <button type ="reset">reset</button>
</div>

</body>

<script>
//use doc.ready to wrap functions after page loads
$(document).ready(function(){
    //create a player 1 to test
    var player = 1;

    //make a click event for the class sqaures
    $('.square').on("click", function(event){

        //store the square class into $(this)
        var squareSelected = $(this);
        //make an if else statenent that adds the class "x" || "o" to your html to show it has been selected
        if(squareSelected.hasClass("fa fa-times fa-4x") || squareSelected.hasClass("fa fa-circle-o fa-4x")){
            alert("you have clicked here already!")
        } else {
            //when square has been selected by player 1 set the player to 2;vice versa
            if(player===1){
                squareSelected.addClass("fa fa-times fa-4x");
                if (checkWin("fa fa-times fa-4x")){
                    alert("Congrats! Player " + player + " has WON!")
                } else {
                player = 2;
                }
            } else {
                squareSelected.addClass("fa fa-circle-o fa-4x");
                if (checkWin("fa fa-circle-o fa-4x")){
                    alert("Congrats! Player " + player + " has WON!")
                } else {
                player = 1;

                }
            }
        }
    });

    //check if player won
    //if player has 3 across,3 up/down, or 3 diagnal they win
    function checkWin(symbol){
        if($(".sq1").hasClass(symbol) && $(".sq2").hasClass(symbol) && $(".sq3").hasClass(symbol)){
            return true
        } else if($(".sq4").hasClass(symbol) && $(".sq5").hasClass(symbol) && $(".sq6").hasClass(symbol)){
            return true
        } else if($(".sq7").hasClass(symbol) && $(".sq8").hasClass(symbol) && $(".sq9").hasClass(symbol)){
            return true
        } else if($(".sq1").hasClass(symbol) && $(".sq4").hasClass(symbol) && $(".sq7").hasClass(symbol)){
            return true
        } else if($(".sq2").hasClass(symbol) && $(".sq5").hasClass(symbol) && $(".sq8").hasClass(symbol)){
            return true
        } else if($(".sq3").hasClass(symbol) && $(".sq6").hasClass(symbol) && $(".sq9").hasClass(symbol)){
            return true
        } else if($(".sq1").hasClass(symbol) && $(".sq5").hasClass(symbol) && $(".sq9").hasClass(symbol)){
            return true
        } else if($(".sq3").hasClass(symbol) && $(".sq5").hasClass(symbol) && $(".sq7").hasClass(symbol)){
            return true
        } else {
            return false;
        }
    }
</script>

1 个答案:

答案 0 :(得分:1)

您可以检查此测试的平局:

$(".fa-times, .fa-circle-o").length == 9

else声明的if (checkWin(...))块中执行该测试。

清除董事会:

$(".square").removeClass("fa-times fa-circle fa fa-4x");

你可以把它放在一个点击处理程序中,用于&#34;重置&#34;按钮。

您可以对代码应用其他一些改进:

  • 当玩家为1或2时,避免重复代码:使用变量添加类,并使用player切换player = 3 - player
  • 在不再发生任何事情的情况下使用return退出该功能,展平您的代码
  • 从开始(在HTML中)已经fafa-4x应用到每个方块,因此您不需要在代码中再管理它。
  • 删除sq1sq2,...类,因为您可以使用$('.square').get(i) jQuery方法分别引用每个方块
  • 使用.is()在一次通话中检查多个班级
  • 使用someevery数组方法获取更短的代码来测试获胜。
  • 添加测试,以便用户在游戏赢得胜利后无法继续点击。

以下是应用这些更改后的代码。请注意,我为此代码段设置了较小的网格(通过更改square的CSS,并使用fa-2x代替fa-4x):

&#13;
&#13;
// In HTML: already assign classes fa and fa-4x, so you don't need to manage
//          those anymore.
$(document).ready(function(){
    var player = 1;
    // Define the classes that are used for the two symbols
    var symbols = ['fa-times', 'fa-circle-o'];
    // Get collection of the 9 squares
    var $squares = $(".square");
    // Set the filter to be used to identify occupied square(s)
    var occupied = "." + symbols.join(", .");

    $('.square').on("click", function(event){
        // Add a test to avoid play continues after game already ended
        if (!player) {
            alert("Game is already over. Click reset to start a new game.")
            return;
        }
        var squareSelected = $(this);
        // Use .is() for shorter syntax, only testing two classes
        if(squareSelected.is(occupied)){
            alert("you have clicked here already!");
            return; // Exit, to make rest of code more flat
        }
        // Get name of class to use:
        var symbol = symbols[player-1];
        squareSelected.addClass(symbol);
        if (checkWin(symbol)){
            alert("Congrats! Player " + player + " has WON!");
            player = 0; // Avoid that play continues in this state.
            return; // Exit, to make rest of code more flat
        }
        // Test for a tie
        if ($squares.filter(occupied).length == 9) {
            alert("Game over. It is a tie.");
            player = 0; // Avoid that play continues in this state.
            return;
        }
        // Toggle player between 1 and 2:
        player = 3 - player;
    });

    function checkWin(symbol){
        // Use more generic & functional code to test for 3-in-a-row 
        var lines = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ];
        // Return whether some of the lines have the symbol in every cell 
        return lines.some(function (line) {
            return line.every(function (i) {
                return $squares.eq(i).hasClass(symbol);
            });
        });
    }
    
    $('#reset').click(function reset() {
        player = 1;
        // Remove all symbols
        $(".square").removeClass(symbols.join(" "));
    });
});
&#13;
@import url("https://fonts.googleapis.com/css?family=Lobster");
body {
    background-color: #21c6be;
}

h1 {
    font-family: "Lobster", cursive;
    text-align: center;
    color: #c621b3;
    background-color: #236d72;
}

#gameboard {
    width: 360px;
    margin: 20px auto 0 auto;
}

.row {
    clear: both;
    overflow: hidden;
}

.square {
    float: left;
    width: 60px;
    height: 40px;
    cursor: crosshair;
    text-align: center;
    padding-top: 20px;
}

.bottom {
    border-bottom: 1px solid black;
}

.right {
    border-right: 1px solid black;
}

button {
    color: #c621b3;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://use.fontawesome.com/703129f3e9.js"></script>

<!--<h1>Tic-Tac-Toe</h1>-->
<div id = "gameboard">
  <div class= "row">
    <div class = "square fa fa-2x bottom right"></div>
    <div class = "square fa fa-2x bottom right"></div>
    <div class = "square fa fa-2x bottom"></div>
  </div>
  <div class= "row">
    <div class = "square fa fa-2x bottom right"></div>
    <div class = "square fa fa-2x bottom right"></div>
    <div class = "square fa fa-2x bottom"></div>
  </div>
  <div class= "row">
    <div class = "square fa fa-2x right"></div>
    <div class = "square fa fa-2x right"></div>
    <div class = "square fa fa-2x"></div>
  </div>
  <button id ="reset" type ="reset">reset</button>
</div>
&#13;
&#13;
&#13;