Skip to content

Commit

Permalink
Corrigir lógica de adicionar jogada e verificar vitória
Browse files Browse the repository at this point in the history
  • Loading branch information
zdearo committed Apr 9, 2024
1 parent c7cd6d1 commit 36c399d
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions script.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,58 +8,75 @@ let currentPlayerDisplay = document.getElementById('current-player');

table.forEach((square, i) => {
square.addEventListener('click', () => {
// Se a casa estiver vazia, adiciona a jogada
if (table[i].innerHTML === '') {
addMove(i);
addMove(i)
addHistory(i);
verifyVictory();
verifyVictory()
alterPlayer();
}
});
});

function addMove(index) {
// Adiciona a jogada na tabela
async function addMove(index) {
const move = document.createElement('div');
move.classList.add(currentPlayer);
table[index].appendChild(move);
moveNumber++;
}

// Alterna o jogador atual
function alterPlayer() {
currentPlayer = currentPlayer === 'cross' ? 'circle' : 'cross';
currentPlayerDisplay.innerHTML = currentPlayer === 'cross' ? 'X' : 'O';
currentPlayerDisplay.style.color = currentPlayer === 'cross' ? '#0000ff' : '#ff0000';
}

function verifyVictory(){
// Verifica se houve vitória
async function verifyVictory(){
const winningCombos = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
];

let victoryFound = false;

// Itera sobre os combos vencedores e verifica se algum foi completado
winningCombos.forEach(combo => {
const [a, b, c] = combo;

//Se o combo foi completado, pinta os quadrados e exibe o alerta de vitória
if (table[a].innerHTML && table[a].innerHTML === table[b].innerHTML && table[a].innerHTML === table[c].innerHTML) {
table[a].style.backgroundColor = '#4a6d42';
table[b].style.backgroundColor = '#4a6d42';
table[c].style.backgroundColor = '#4a6d42';
let winningPlayer = currentPlayer;
setTimeout(() => {
alert(`Player ${currentPlayer === 'cross' ? 'Circle' : 'Cross'} wins!`);
alert(`Player ${winningPlayer} wins!`);
resetGame();
}, 100);
}else if (moveNumber >= 7) {
table[history[moveNumber - 6].position].innerHTML = '';
victoryFound = true;
}
});

// Se não houve vencedor e o jogo está no 9º movimento, apaga a jogada mais antiga
if (!victoryFound && moveNumber >= 7) {
console.log('moveNumber', moveNumber);
table[history[moveNumber - 7].position].innerHTML = '';
}
}

// Adiciona a jogada no histórico
function addHistory(position) {
history.push({ moveNumber: moveNumber, player: currentPlayer, position: position });
const historyItem = document.createElement('li');
historyItem.innerHTML = `Move ${moveNumber}: ${currentPlayer === 'cross' ? 'X' : 'O'} at position ${position}`;
historyList.appendChild(historyItem);
}

// Reinicia o jogo
function resetGame() {
table.forEach(square => {
square.innerHTML = '';
Expand Down

0 comments on commit 36c399d

Please sign in to comment.