Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementação Distancia Mahattan, Número de Peças fora do Lugar #11

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 40 additions & 19 deletions puzzle8.html
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
cursor: pointer;
user-select: none;
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3);
transition: all 0.3s ease;
}

.tile.empty {
Expand All @@ -57,7 +58,7 @@
color: #333;
}

.inversions {
.inversions, .manhattan, .out-of-place {
margin-top: 10px;
font-size: 16px;
color: #555;
Expand Down Expand Up @@ -108,6 +109,12 @@
<div class="inversions" id="inversionsCount">
Inversões: 0 (Paridade: par)
</div>
<div class="manhattan" id="manhattanDistance">
Distância de Manhattan: 0
</div>
<div class="out-of-place" id="outOfPlaceCount">
Peças fora do lugar: 0
</div>
<div class="move-count" id="moveCount">
Número de jogadas: 0
</div>
Expand All @@ -118,12 +125,13 @@
const boardStateDisplay = document.getElementById('boardState');
const inversionsDisplay = document.getElementById('inversionsCount');
const moveCountDisplay = document.getElementById('moveCount');
const manhattanDisplay = document.getElementById('manhattanDistance');
const outOfPlaceDisplay = document.getElementById('outOfPlaceCount');
const shuffleButton = document.getElementById('shuffleButton');

const goalState = [1, 2, 3, 4, 5, 6, 7, 8, 0];
let moveCount = 0;

// Inicializa o estado do tabuleiro
let boardState = Array.from(tiles).map(tile => parseInt(tile.dataset.value));

function calculateInversions(state) {
Expand All @@ -138,16 +146,40 @@
return inversions;
}

function calculateManhattanDistance(state) {
let distance = 0;
for (let i = 0; i < state.length; i++) {
if (state[i] !== 0) {
const goalPosition = goalState.indexOf(state[i]);
const currentRow = Math.floor(i / 3);
const currentCol = i % 3;
const goalRow = Math.floor(goalPosition / 3);
const goalCol = goalPosition % 3;
distance += Math.abs(currentRow - goalRow) + Math.abs(currentCol - goalCol);
}
}
return distance;
}

function calculateOutOfPlace(state) {
return state.reduce((count, value, index) => {
return (value !== 0 && value !== goalState[index]) ? count + 1 : count;
}, 0);
}

function updateDisplay() {
// Exibe o estado do tabuleiro na página
boardStateDisplay.textContent = `Estado atual: [${boardState.join(', ')}]`;

// Calcula e exibe o número de inversões e a paridade
const inversions = calculateInversions(boardState);
const parity = inversions % 2 === 0 ? "par" : "ímpar";
inversionsDisplay.textContent = `Inversões: ${inversions} (Paridade: ${parity})`;

// Exibe o número de jogadas
const manhattanDistance = calculateManhattanDistance(boardState);
manhattanDisplay.textContent = `Distância de Manhattan: ${manhattanDistance}`;

const outOfPlace = calculateOutOfPlace(boardState);
outOfPlaceDisplay.textContent = `Peças fora do lugar: ${outOfPlace}`;

moveCountDisplay.textContent = `Número de jogadas: ${moveCount}`;
}

Expand All @@ -158,14 +190,12 @@
}

function shuffleBoard() {
// Embaralha o estado do tabuleiro
do {
boardState = boardState.sort(() => Math.random() - 0.5);
} while (calculateInversions(boardState) % 2 !== 0); // Garante que o estado seja resolvível
} while (calculateInversions(boardState) % 2 !== 0);

moveCount = 0; // Reseta o contador de jogadas
moveCount = 0;

// Atualiza o conteúdo visual
tiles.forEach((tile, index) => {
tile.textContent = boardState[index] === 0 ? "" : boardState[index];
tile.dataset.value = boardState[index];
Expand All @@ -177,11 +207,10 @@
}
});

// Atualiza as exibições
updateDisplay();
}

updateDisplay(); // Atualiza a exibição inicialmente
updateDisplay();

grid.addEventListener('click', (e) => {
const tile = e.target;
Expand All @@ -197,7 +226,6 @@
const tileIndex = Array.from(tiles).indexOf(tile);
const emptyTileIndex = Array.from(tiles).indexOf(emptyTile);

// Define movimentos válidos (esquerda, direita, cima, baixo)
const validMoves = {
0: [1, 3],
1: [0, 2, 4],
Expand All @@ -211,24 +239,17 @@
};

if (validMoves[emptyTileIndex].includes(tileIndex)) {
// Troca de posição entre a peça clicada e a peça vazia
[boardState[tileIndex], boardState[emptyTileIndex]] = [boardState[emptyTileIndex], boardState[tileIndex]];

// Atualiza o conteúdo visual
tile.textContent = boardState[tileIndex] === 0 ? "" : boardState[tileIndex];
emptyTile.textContent = boardState[emptyTileIndex] === 0 ? "" : boardState[emptyTileIndex];

// Troca as classes para manter a peça vazia correta
tile.classList.add('empty');
emptyTile.classList.remove('empty');

// Incrementa o contador de jogadas
moveCount++;

// Atualiza as exibições
updateDisplay();

// Verifica se o estado meta foi alcançado
checkGoalState();
}
}
Expand Down