2016-09-04 3 views
1

Я строю игру с тик-таком.Как я могу переносить свой элемент в функцию обработчика событий?

Когда плата загружена, я создаю прослушиватели событий для всех ящиков платы. Он будет прослушивать щелчок, затем он вызывает функцию placePiece.

В местеПублица функции, как я могу настроить целевой прямоугольник? Могу ли я использовать это?

Прежде всего, мне нужно проверить, было ли поле уже заполнено или нет. Если это не так, то в зависимости от того, currentPlayer является player1 или player2, он будет либо заполнить топор или 0.

Вот мой код:

// Add programming, so that when the player clicks the start button the start screen disappears, the board appears, and the game begins. 
function loadBoard() { 
    document.body.innerHTML = originalHTML; 

    player1 = new Player(player1); 
    player2 = new Player(player2); 

    var startingPlayerNum = Math.floor((Math.random() * 2) + 1); 
    console.log(startingPlayerNum); 

    if(startingPlayerNum === 1){ 
     player1.currentPlayer = true; 
     currentPlayer = player1; 
    } else { 
     player2.currentPlayer === true; 
     currentPlayer = player2 
    } 

    //Add clickhandlers for boxes 
    var a1 = document.getElementById('a1').addEventListener("click", placePiece); 
    var a2 = document.getElementById('a2').addEventListener("click", placePiece); 
    var a3 = document.getElementById('a3').addEventListener("click", placePiece); 
    var b1 = document.getElementById('b1').addEventListener("click", placePiece); 
    var b2 = document.getElementById('b2').addEventListener("click", placePiece); 
    var b3 = document.getElementById('b3').addEventListener("click", placePiece); 
    var c1 = document.getElementById('c1').addEventListener("click", placePiece); 
    var c2 = document.getElementById('c2').addEventListener("click", placePiece); 
    var c3 = document.getElementById('c3').addEventListener("click", placePiece); 

    currentPlayerFlag() 
}; 

// Добавляем игру следуя этим правилам , // Play чередует X и О.

// The current player is indicated at the top of the page -- the box with the symbol O or X is highlighted for the current player. 
function currentPlayerFlag() { 
    if(currentPlayer === player1){ 
     document.getElementById('player1').classList.add("active"); 
     document.getElementById('player2').className = "players"; 
    } 
    if(currentPlayer === player2){ 
     document.getElementById('player2').classList.add("active"); 
     document.getElementById('player1').className = "players"; 
    } 
}; 


// When the current player mouses over an empty square on the board, it's symbol the X or O should appear on the square. 
    // You can do this using the x.svg or o.svg graphics (hint use JavaScript to set the background-image property for that box.) 
function placePiece() { 


    // Players can only click on empty squares. When the player clicks on an empty square, attach the class box-filled-1 (for O) or box-filled-2 (for X) to the square. 

    //How do I select the right tile? 
    if(//SPACE IS NOT EMPTY ?) { 
     if(currentPlayer === player1){ 

      player1.currentPlayer = false; 
      player2.currentPlayer = true; 
      currentPlayer = player2; 
     } 
     if(currentPlayer === player2){ 

      player2.currentPlayer = false; 
      player1.currentPlayer = true; 
      currentPlayer = player1; 
     } 

     gameState(); 
    } 
}; 

Спасибо!

+0

Почему вы сохраните возвращаемое значение 'addEventListener' в переменные? – Li357

+0

* «Как я могу настроить целевой флажок? Могу ли я использовать« это »?» * - Да. Вы пробовали это? – nnnnnn

+0

Наверное, потому что я идиот, @ Андрю, я исправил это. @nnnnnn, я пытался сделать это с моей функцией MouseOver: 'функция MouseOver() { \t // Сделайте это с помощью x.svg или o.svg график \t если (currentPlayer === player1) { \t \t this.style.backgroundImage = "url (../ tic-tac-toe-v3/img/o.svg)"; \t} else { \t \t this.style.backgroundImage = "url (../ tic-tac-toe-v3/img/x.svg)"; \t} }; ' с этим EventListener:. ' document.getElementById ('a1') addEventListener ("Mouseover", MouseOver); ' – gloopit

ответ

0

Попробуйте что-то вроде этого

var a1 = document.getElementById('a1').addEventListener("click", function() {placePiece(this)}); 

и настроить placePiece соответственно:

function placePiece(x) { 
    ...