2016-02-29 3 views
0

Я пишу игру TicTacToe, и у меня возникли проблемы с добавлением счетчика выигрышей, чтобы узнать, сколько игр выиграл игрок X и сколько игр выиграл игрок O. Прямо сейчас, у меня есть JS-код с выражением if. Если alert = Winner is X, то xWinCount ++, но я не уверен, что это правильный путь. Спасибо за любую помощь, я очень благодарен.Добавить прирост на основе оповещения

HTML код:

<div class="container"> 
    <div class="col-md-12 header"> 
    <h1 class="banner">Previous Games</h1> 

    <h1 class="banner">Rules</h1> 

    <h1 class="banner-right">List of Wins</h1> 
    </div> 
    <div class="row"> 
    <div class="col-md-4 nine hidden-xs red"></div> 
    <!--previous game--> 

    <div class="col-md-4 hidden-xs green-bg"> 
     <!--rules + who's turn is it --> 
     <p>Classic Tic-Tac-Toe game.</br> 
     </br> Match three X's or three O's in a line vertically, horizontally or diagonally to win!</p> 
    </div> 
    <div class="col-md-4 hidden-xs blue"> 
     <!-- List of wins --> 
     <div class="win-chart"> 
     <p class="win-chart">X has won:</p> 
     <p id="xWinCount" class="xWinCount win-chart">0</p> 
     <p class="win-chart">time(s)</p> 
     </br> 
     <p class="win-chart">O has won:</p> 
     <p id="oWinCount" class="xWinCount win-chart">0</p> 
     <p class="win-chart">time(s)</p> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="col-md-4 nine hidden-xs red"></div> 
     <div class="col-md-4 nine" id="board"> 
     <div class="col-md-4 innerNine empty borderBottom col-xs-4"></div> 
     <div class="col-md-4 innerNine empty borderBottom borderLeftAndRight col-xs-4"></div> 
     <div class="col-md-4 innerNine empty borderBottom col-xs-4"></div> 
     <div class="col-md-4 innerNine empty col-xs-4"></div> 
     <div class="col-md-4 innerNine empty borderLeftAndRight col-xs-4"></div> 
     <div class="col-md-4 innerNine empty col-xs-4"></div> 
     <div class="col-md-4 innerNine empty borderTop col-xs-4"></div> 
     <div class="col-md-4 innerNine empty borderTop borderLeftAndRight col-xs-4"></div> 
     <div class="col-md-4 innerNine empty borderTop col-xs-4"></div> 
     </div> 
     <div class="col-md-4 hidden-xs"></div> 
     <!--blue not needed --> 
    </div> 
    <div class="row"> 
     <div class="col-md-4 nine red"></div> 
     <div class="col-md-4"> 
     <button id="newGame" class="btn btn-success btn-lg" type="button"><span class="glyphicon glyphicon-repeat"></span>Restart Game </button> 
     <a href=" " button id="newGame" class="btn btn-primary btn-lg" type="button"><span class="glyphicon glyphicon-repeat"></span>Reset Scores</button></a> 
     </div> 
     <div class="col-md-4"> </div> 
     <!--blue not needed --> 
    </div> 
    </div> 

JS код:

$(document).ready(function() { 

    var circleOrEx = "o"; // who gets first turn, right now circle goes first 
    var isGameInProgress = true; // when the document loads, the tictactoe board is an active game 
    var winningCombos = { // the game board is a series of nine square boxes, but since this is an array, the values for earch box is 0 to 8. these values outline the winning combinations starting from each possible square on the board. the board is writen out like this: 

     // 0 | 1 | 2 
     // --------- 
     // 3 | 4 | 5 
     // --------- 
     // 6 | 7 | 8 

    0: [ //0 is key (winning combinations starting from the top left square) 
     [1, 2], //if the user enters in three of the same values across the top three squares, they win 
     [3, 6], //if the user enters in three of the same values down the far left column, they win 
     [4, 8] //if the user enters in three of the same values diagonally from the top left to bottom      right, they win 
    ], 
    1: [ //(winning combinations starting from the top middle square) 
     [0, 2], //if the user enters in three of the same values across the top three squares, they win 
     [4, 7] //if the user enters in three of the same values down the middle column, they win 

    ],  //there are no diagonal winning combinations for values 1, 3, 5, 7 

    2: [ //(winning combinations starting from the top right square) 
     [0, 1], //if the user enters in three of the same values across the top three squares, they win 
     [5, 8], //if the user enters in three of the same values down the far right column, they win 
     [4, 6] //if the user enters in three of the same values diagonally from the top right to bottom      left, they win 
    ], 
    3: [ //(winning combinations starting at the middle square on the far left column) 
     [0, 6], //if the user enters in three of the same values down the far left column, they win 
     [4, 5] //if the user enters in three of the same values across the middle row, they win 
    ], 
    4: [ //(winning combinations starting at the center square) 
     [1, 8], //BUG IN THE CODE, this should not be a winning combination 
     [2, 6], //if the user enters in three of the same values diagonally from the top right to bottom      left, they win 
     [1, 7], //if the user enters in three of the same values down the middle column, they win 
     [3, 5] // if the user enters in three of the same values across the middle row, they win 
    ], 
    5: [ //(winning combinations starting from the middle square in the far right column) 
     [2, 8], //if the user enters in three of the same values down the far right column, they win 
     [3, 4] // if the user enters in three of the same values across the middle row, they win 
    ], 
    6: [ //(winning combinations starting from the bottom left square) 
     [0, 3], //if the user enters in three of the same values down the far left column, they win 
     [2, 4], //if the user enters in three of the same values diagonally from the top left to bottom      right, they win 
     [7, 8] //if the user enters in three of the same values across the bottom three squares, they win 
    ], 
    7: [ //(winning combinations starting from the bottom middle square) 
     [1, 4],//if the user enters in three of the same values down the middle column, they win 
     [6, 8] //if the user enters in three of the same values across the bottom three squares, they win 
    ], 
    8: [ //(winning combinations starting from the bottom right square) 
     [0, 4], //if the user enters in three of the same values diagonally from the bottom right to the top    left, they win 
     [2, 5], //if the user enters in three of the same values down the far right column, they win 
     [6, 7] //if the user enters in three of the same values across the bottom three squares, they win 
    ] 
    }; 

    // when the user clicks on the board, the function runs, and the game is in progress 
    $("#board").find("div").on("click", function() { 

    if (isGameInProgress && $(this).hasClass("empty")) { /// within the #board remove the empty class and add either an X or an O value to the square when it is is clicked 
     $(this).removeClass("empty").append("<span class='" + circleOrEx + "'>" + circleOrEx + "</span"); //allows user to input X or O value in the square 

     checkIfWon($(this).index(), circleOrEx); //function determines the turn cycle of the game 

     if (circleOrEx === "o") { // if O has played their turn, run code on line 68 
     circleOrEx = "x"; // now it is X's turn 
     } else { 
     circleOrEx = "o"; // X has played their turn, now it is circle's turn 
     } 
    } 

    }); 

    // once you click the button with the 'newGame' id, run the function 
    $("#newGame").on("click", function() { 

    var boardSquares = $("#board").find("div"); //boardSquares now becomes every div element within #board, which is each of the nine blank squares that make up the tic tac toe game 
    var firstEmptyMemorySquare = $(".container").find(".nine").filter(function() { //returns a value for firstEmptyMemorySquare if the function passes these requirements place the #board within the class nine that is in the containter. (once the game clicking the refresh button, place the previous board in an empty section of the page) 
     return $.trim($(this).text()) === "" && $(this).children().length === 0; 
    }).not("#board").first(); 

    if (firstEmptyMemorySquare.length == 1) { //placing a previously played game in an EmptyMemorySquare 
     firstEmptyMemorySquare.html($("#board").html()); 
    } else { 
     $(".container").find(".nine").not("#board").empty(); 
     $(".container").find(".nine").first().html($("#board").html()); 
    } 

    //deletes anything in the empty class to games that are in progress, which allows user to enter X's or O's in the boardSquares 
    boardSquares.each(function() { 
     $(this).addClass("empty").empty(); 
    }) 
    isGameInProgress = true; 
    }) 

    //checks if a player won. chosenSquare is the final value in a winning combination; the possible values for the chosenSquare parameter is [0] - [8] 
    function checkIfWon(chosenSquare) { 

    var mulitArr = winningCombos[chosenSquare]; 
    var playerWon; 

    for (var i = 0; i < mulitArr.length; i++) { //the nested loop provides the length of the multidimensional array 
     playerWon = true; 
     for (var j = 0; j < mulitArr[i].length; j++) { //value of j starts at zero so the user must enter three values within a winning combination. If j initially starts at 1 user only needs to match two of the same values within a winning combination. If j => 2 the user only needs to match one value of a winning combination (which would be any square on the board) 
     if (!$("#board").find("div").eq(mulitArr[i][j]).find("span").hasClass(circleOrEx)) { //Explain this condition 
      playerWon = false; 
     } 
     } 

     if (playerWon) { //remaining lines affect the board when a player enters a winning combination 

     for (var j = 0; j < mulitArr[i].length; j++) { 
      $("#board").find("div").eq(mulitArr[i][j]).find("." + circleOrEx).addClass("green"); //makes the first two inputs of the winning comination the color green 
     } 
     $("#board").find("div").eq(chosenSquare).find("." + circleOrEx).addClass("green"); //makes the last   input of the winning combination (chosenSquare) the color green 
     alert("Winner is " + circleOrEx.toUpperCase() + "!"); //alert "Winner is X" or "Winner is O" 
var xWinCount = 0; 
    var xWinCount = 0; 
     if (playerWon = Ex){ 
      document.getElementById('xWinCount'); 
      var xWin = xWinCount.innerHTML; 
      xWinin++; 
      xWinCount.innerHTML = x-win; 
      } 
     else{ 
     document.getElementById('oWinCount'); 
     var oWin = oWinCount.innerHTML; 
     oWin++; 
     oWinCount.innerHTML = o-win; 
     } 
     isGameInProgress = false; //since a player has won, the game is no longer in progress 
     return false; //this exits the loop 
     } 
    } 


    } 
}) 
+0

К сожалению, alert() не может вернуть данные. –

+2

вы также можете рассмотреть возможность сборки jsfiddle. thats справедливый бит кода, чтобы понять, но соответствующий бит, чтобы помочь отлаживать не будет все html и css. –

+0

@ m0atz Я сделал документ jsfiddle, к сожалению, я не могу получить раздел результатов для отображения полного экрана https://jsfiddle.net/evdd0qv9/1/ – fasteddie

ответ

0

упускают эту строку document.getElementById('xWinCount'); не присвоенное переменной, кажется, вы хотите xWinCount = document.getElementById('xWinCount'); же для oWinCount

Вы будете иметь элемент, который innerHTML должен держать ваш текущий балл, и да, позже вы можете изменить или увеличить его va ЛУЭ.

0

Я собираюсь предположить, что все работает до тех пор, пока функция checkIfWon не срабатывает, потому что это довольно немного кода для прошивки.

Увеличение количества выигрышей должно быть довольно тривиальным. Глядя на код, который у вас есть, я вижу пару проблем.

// The first problem is your function. You pass it 2 arguments but it only catches 1 
    // The second argument is what character 'won', so it should look something like this: 
    // function checkIfWon(chosenSquare, winningPlayer) 
    function checkIfWon(chosenSquare) 

    var xWinCount = 0; 
    // playerWon is a boolean. You need to know if the player won, but also which player won. 
    // You should use the variable passed in through the function parameters 
    // if (winningPlayer == "x" && playerWon) 
    if (playerWon = Ex){ 
     // document.getElementById returns an object. 
     // To grab the innerHTML attribute from an object, you can do something like this: 
     // xWinCount = document.getElementById('xWinCount').innerHTML; 
     document.getElementById('xWinCount'); 
     var xWin = xWinCount.innerHTML; 

     // Assuming you get the above code working, 
     // the increment and assignment code should look something like this: 
     // xWinCount++; 
     // document.getElementById('xWinCount').innerHTML = xWinCount; 
     xWinin++; 
     xWinCount.innerHTML = x-win; 
    } 

В заявлении else должны быть указаны те же проблемы, что и выше.

Вот моя версия, используя jQuery, так как это немного проще, и похоже, что она доступна на основе другого кода в вашем проекте. Вы должны уметь вычислять часть «else» из этого фрагмента кода.

function checkIfWon(chosenSquare, winningPlayer) { 
    if (playerWon) { 
     if (winningPlayer == 'x') { 
      // Grab the current win count 
      var xWinCount = $('#xWinCount').val(); 

      // Increment the count 
      xWinCount++; 

      // Assign the new count 
      $('#xWinCount').val(xWinCount); 
     } 
    } 
} 
Смежные вопросы