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

Velha renan kelvin #26

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
53 changes: 52 additions & 1 deletion puzzle8.html
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@
color: #333;
}

.inversions {
.inversions,
.manhattan,
.misplaced-tiles,
.move-log {
margin-top: 10px;
font-size: 16px;
color: #555;
Expand Down Expand Up @@ -88,6 +91,7 @@
</style>
</head>
<body>
<h1>Renan e Kelvin - Puzzle8</h1>
<div class="container">
<div class="grid">
<div class="tile" data-value="1">1</div>
Expand All @@ -108,6 +112,15 @@
<div class="inversions" id="inversionsCount">
Inversões: 0 (Paridade: par)
</div>
<div class="manhattan" id="manhattanDistance">
Distância Manhattan: 0
</div>
<div class="misplaced-tiles" id="misplacedTilesCount">
Peças fora do lugar: 0
</div>
<div class="move-log" id="moveLog">
Trocas: Nenhuma
</div>
<div class="move-count" id="moveCount">
Número de jogadas: 0
</div>
Expand All @@ -117,11 +130,15 @@
const grid = document.querySelector('.grid');
const boardStateDisplay = document.getElementById('boardState');
const inversionsDisplay = document.getElementById('inversionsCount');
const manhattanDisplay = document.getElementById('manhattanDistance');
const misplacedTilesDisplay = document.getElementById('misplacedTilesCount');
const moveLogDisplay = document.getElementById('moveLog');
const moveCountDisplay = document.getElementById('moveCount');
const shuffleButton = document.getElementById('shuffleButton');

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

// Inicializa o estado do tabuleiro
let boardState = Array.from(tiles).map(tile => parseInt(tile.dataset.value));
Expand All @@ -138,6 +155,25 @@
return inversions;
}

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

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

function updateDisplay() {
// Exibe o estado do tabuleiro na página
boardStateDisplay.textContent = `Estado atual: [${boardState.join(', ')}]`;
Expand All @@ -147,8 +183,19 @@
const parity = inversions % 2 === 0 ? "par" : "ímpar";
inversionsDisplay.textContent = `Inversões: ${inversions} (Paridade: ${parity})`;

// Calcula e exibe a Distância Manhattan
const manhattanDistance = calculateManhattanDistance(boardState);
manhattanDisplay.textContent = `Distância Manhattan: ${manhattanDistance}`;

// Calcula e exibe a quantidade de peças fora do lugar
const misplacedTiles = calculateMisplacedTiles(boardState);
misplacedTilesDisplay.textContent = `Peças fora do lugar: ${misplacedTiles}`;

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

// Exibe o log de trocas
moveLogDisplay.textContent = `Trocas: ${moveLog.join(', ') || 'Nenhuma'}`;
}

function checkGoalState() {
Expand All @@ -164,6 +211,7 @@
} while (calculateInversions(boardState) % 2 !== 0); // Garante que o estado seja resolvível

moveCount = 0; // Reseta o contador de jogadas
moveLog = []; // Limpa o log de trocas

// Atualiza o conteúdo visual
tiles.forEach((tile, index) => {
Expand Down Expand Up @@ -214,6 +262,9 @@
// Troca de posição entre a peça clicada e a peça vazia
[boardState[tileIndex], boardState[emptyTileIndex]] = [boardState[emptyTileIndex], boardState[tileIndex]];

// Registra a troca
moveLog.push(`[${tileIndex}, ${emptyTileIndex}]`);

// Atualiza o conteúdo visual
tile.textContent = boardState[tileIndex] === 0 ? "" : boardState[tileIndex];
emptyTile.textContent = boardState[emptyTileIndex] === 0 ? "" : boardState[emptyTileIndex];
Expand Down
108 changes: 65 additions & 43 deletions velha.html
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,9 @@
background-color: #007bff;
color: white;
}
#play-o-button {
background-color: #17a2b8;
color: white;
}
#reset-button:hover {
background-color: #0056b3;
}
#play-o-button:hover {
background-color: #138496;
}
</style>
</head>
<body>
Expand All @@ -128,7 +121,6 @@
</div>
<div id="button-container">
<button id="reset-button">Reiniciar</button>
<button id="play-o-button">Jogar O</button>
</div>
</div>

Expand All @@ -140,64 +132,94 @@ <h3>Próximas Possibilidades</h3>

<script>
const board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let currentPlayer = "X"; // Jogador humano sempre começa com "X"
let gameActive = true;

const cells = document.querySelectorAll('.cell');
const treeRoot = document.getElementById('tree-root');
const resetButton = document.getElementById('reset-button');
const playOButton = document.getElementById('play-o-button');

cells.forEach(cell => {
cell.addEventListener('click', handleClick);
});

resetButton.addEventListener('click', resetGame);
playOButton.addEventListener('click', aiMove);

function handleClick(e) {
const id = e.target.id;
if (board[id] === "" && gameActive) {
if (currentPlayer === "X") {
// Jogada do jogador X
board[id] = currentPlayer;
e.target.textContent = currentPlayer;
e.target.classList.add(currentPlayer);
if (board[id] === "" && gameActive && currentPlayer === "X") {
board[id] = currentPlayer;
e.target.textContent = currentPlayer;
e.target.classList.add(currentPlayer);

if (checkWinner(board, currentPlayer)) {
highlightWinningCells(board, currentPlayer);
alert(currentPlayer + ' venceu!');
gameActive = false;
} else if (board.includes("")) {
currentPlayer = "O";
generateNextMoves(board, currentPlayer, treeRoot);
}
} else if (currentPlayer === "O") {
// Jogada do jogador O via clique do mouse
board[id] = currentPlayer;
e.target.textContent = currentPlayer;
e.target.classList.add(currentPlayer);
if (checkWinner(board, currentPlayer)) {
highlightWinningCells(board, currentPlayer);
alert(currentPlayer + ' venceu!');
gameActive = false;
} else if (board.includes("")) {
currentPlayer = "O";
generateNextMoves(board, currentPlayer, treeRoot);
aiMove(); // IA faz sua jogada logo após a jogada do humano
}
}
}

if (checkWinner(board, currentPlayer)) {
highlightWinningCells(board, currentPlayer);
alert(currentPlayer + ' venceu!');
gameActive = false;
} else if (board.includes("")) {
currentPlayer = "X";
generateNextMoves(board, currentPlayer, treeRoot);
function minimax(board, depth, isMaximizingPlayer, alpha, beta) {
const winner = checkWinner(board, 'X') ? 'X' : (checkWinner(board, 'O') ? 'O' : null);
if (winner === 'X') return -10 + depth;
if (winner === 'O') return 10 - depth;
if (!board.includes("")) return 0;

if (isMaximizingPlayer) {
let maxEval = -Infinity;
for (let i = 0; i < board.length; i++) {
if (board[i] === "") {
board[i] = 'O';
let eval = minimax(board, depth + 1, false, alpha, beta);
board[i] = "";
maxEval = Math.max(maxEval, eval);
alpha = Math.max(alpha, eval);
if (beta <= alpha) break;
}
}
return maxEval;
} else {
let minEval = Infinity;
for (let i = 0; i < board.length; i++) {
if (board[i] === "") {
board[i] = 'X';
let eval = minimax(board, depth + 1, true, alpha, beta);
board[i] = "";
minEval = Math.min(minEval, eval);
beta = Math.min(beta, eval);
if (beta <= alpha) break;
}
}
return minEval;
}
}

function aiMove() {
if (currentPlayer === "O" && gameActive) {
const emptyCells = board.map((val, index) => val === "" ? index : null).filter(val => val !== null);
if (emptyCells.length > 0) {
const randomIndex = emptyCells[Math.floor(Math.random() * emptyCells.length)];
board[randomIndex] = currentPlayer;
cells[randomIndex].textContent = currentPlayer;
cells[randomIndex].classList.add(currentPlayer);
let bestMove;
let bestValue = -Infinity;

for (let i = 0; i < board.length; i++) {
if (board[i] === "") {
board[i] = 'O';
let moveValue = minimax(board, 0, false, -Infinity, Infinity);
board[i] = "";
if (moveValue > bestValue) {
bestValue = moveValue;
bestMove = i;
}
}
}

if (bestMove !== undefined) {
board[bestMove] = currentPlayer;
cells[bestMove].textContent = currentPlayer;
cells[bestMove].classList.add(currentPlayer);

if (checkWinner(board, currentPlayer)) {
highlightWinningCells(board, currentPlayer);
Expand Down