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

Update puzzle8.html #4

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
111 changes: 71 additions & 40 deletions puzzle8.html
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,13 @@
box-shadow: none;
}

.board-state {
margin-top: 20px;
font-size: 18px;
font-weight: bold;
color: #333;
}

.inversions {
.board-state, .inversions, .move-count, .manhattan-distance, .misplaced-tiles, .move-history, .parity-calculator {
margin-top: 10px;
font-size: 16px;
color: #555;
}

.shuffle-button {
.shuffle-button, .calculate-parity-button {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
Expand All @@ -76,14 +69,12 @@
transition: background-color 0.3s;
}

.shuffle-button:hover {
.shuffle-button:hover, .calculate-parity-button:hover {
background-color: #45a049;
}

.move-count {
margin-top: 10px;
font-size: 16px;
color: #555;
.input-board {
margin-top: 20px;
}
</style>
</head>
Expand All @@ -102,14 +93,16 @@
</div>
</div>
<button class="shuffle-button" id="shuffleButton">Sortear Estado Inicial</button>
<div class="board-state" id="boardState">
Estado atual: [1, 2, 3, 4, 5, 6, 7, 8, 0]
</div>
<div class="inversions" id="inversionsCount">
Inversões: 0 (Paridade: par)
</div>
<div class="move-count" id="moveCount">
Número de jogadas: 0
<div class="board-state" id="boardState">Estado atual: [1, 2, 3, 4, 5, 6, 7, 8, 0]</div>
<div class="inversions" id="inversionsCount">Inversões: 0 (Paridade: par)</div>
<div class="move-count" id="moveCount">Número de jogadas: 0</div>
<div class="manhattan-distance" id="manhattanDistance">Distância de Manhattan: 0</div>
<div class="misplaced-tiles" id="misplacedTiles">Peças fora do lugar: 0</div>
<div class="move-history" id="moveHistory">Histórico de Movimentos: []</div>
<div class="input-board">
<input type="text" id="customBoard" placeholder="Digite o estado inicial (ex: 1,2,3,4,5,6,7,8,0)">
<button class="calculate-parity-button" id="calculateParityButton">Calcular Paridade</button>
<div class="parity-calculator" id="parityResult">Paridade: -</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
Expand All @@ -118,12 +111,18 @@
const boardStateDisplay = document.getElementById('boardState');
const inversionsDisplay = document.getElementById('inversionsCount');
const moveCountDisplay = document.getElementById('moveCount');
const manhattanDistanceDisplay = document.getElementById('manhattanDistance');
const misplacedTilesDisplay = document.getElementById('misplacedTiles');
const moveHistoryDisplay = document.getElementById('moveHistory');
const shuffleButton = document.getElementById('shuffleButton');
const calculateParityButton = document.getElementById('calculateParityButton');
const customBoardInput = document.getElementById('customBoard');
const parityResultDisplay = document.getElementById('parityResult');

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

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

function calculateInversions(state) {
Expand All @@ -138,17 +137,48 @@
return inversions;
}

function calculateManhattanDistance(state) {
const goalPositions = {
1: [0, 0], 2: [0, 1], 3: [0, 2],
4: [1, 0], 5: [1, 1], 6: [1, 2],
7: [2, 0], 8: [2, 1], 0: [2, 2]
};

let distance = 0;
state.forEach((value, index) => {
const currentPos = [Math.floor(index / 3), index % 3];
const goalPos = goalPositions[value];
distance += Math.abs(currentPos[0] - goalPos[0]) + Math.abs(currentPos[1] - goalPos[1]);
});

return distance;
}

function calculateMisplacedTiles(state) {
return state.filter((value, index) => value !== goalState[index] && value !== 0).length;
}

function checkParityForInput(inputState) {
const inversions = calculateInversions(inputState);
return inversions % 2 === 0 ? "par" : "ímpar";
}

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
moveCountDisplay.textContent = `Número de jogadas: ${moveCount}`;

const manhattanDistance = calculateManhattanDistance(boardState);
manhattanDistanceDisplay.textContent = `Distância de Manhattan: ${manhattanDistance}`;

const misplacedTiles = calculateMisplacedTiles(boardState);
misplacedTilesDisplay.textContent = `Peças fora do lugar: ${misplacedTiles}`;

moveHistoryDisplay.textContent = `Histórico de Movimentos: ${JSON.stringify(moveHistory)}`;
}

function checkGoalState() {
Expand All @@ -158,14 +188,13 @@
}

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;
moveHistory = [];

// 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 +206,10 @@
}
});

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

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

grid.addEventListener('click', (e) => {
const tile = e.target;
Expand All @@ -192,12 +220,21 @@

shuffleButton.addEventListener('click', shuffleBoard);

calculateParityButton.addEventListener('click', () => {
const inputState = customBoardInput.value.split(',').map(Number);
if (inputState.length === 9 && inputState.every(n => n >= 0 && n <= 8)) {
const parity = checkParityForInput(inputState);
parityResultDisplay.textContent = `Paridade: ${parity}`;
} else {
parityResultDisplay.textContent = `Entrada inválida. Insira um estado de 9 números separados por vírgula.`;
}
});

function moveTile(tile) {
const emptyTile = document.querySelector('.tile.empty');
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 +248,18 @@
};

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++;
moveHistory.push([...boardState]);

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

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