Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

[Dúvida] Jogo da Memória falho

Olá, tudo bem?

Estou tentando fazer um jogo da memória. Mas ele nem consegue executar. Por causa disso, estou enviando todos os codigos (no total são 4):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Correção na declaração do cabeçalho meta -->
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" type="text/css" href="./styles/style.css"/>
    <!-- Remoção do link para a fonte Righteous, já que não está sendo utilizado -->
    <title>Memória</title>
</head>
<body>
    <!-- Conteúdo do jogo -->
    <div id="gameBoard">
        <!-- Cartas do jogo -->
    </div>
    <a class="banner" href="">
        <img src="./images/banner.jpg" alt="Curso DAlura">
    </a>
    <!-- Div de game over -->
    <div id="gameOver">
        <!-- Mensagem de parabéns -->
        <div>
            Parabéns, você completou o jogo!
        </div>
        <!-- Botão para reiniciar -->
        <button id="restart" onclick="restart()">Jogue novamente</button>
    </div>
    <!-- Scripts -->
    <!-- Correção no caminho dos scripts JavaScript -->
    <script src="./script/game.js"></script>
    <script src="./script/script.js"></script>
</body>
</html>

O anterior foi um HTML, agora vem o CSS:


body{
    font-family: 'Righteous', sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #c7cdd3;
}

.banner > img{
    max-width: 300px;
}

.card{
    width: 150px;
    height: 150px;
    position: relative;
    transform-style: preserve-3d;
    transition: transform .5s;
}

.card_back, .card_front{
    width: 100%;
    height: 100%;
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 20px;
    box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.45);
    backface-visibility: hidden;
}

.flip{
    transform: rotateY(180deg);
}

.card_front{
    transform: rotateY(180deg);
    background-color: #101c2c;
}

.card_back{
    background-color: #05c3ff;
    font-size: 30px;
}

#gameOver{
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.9);
    color: white;
    font-size: 50px;
    display: none;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    top: 0;
}

#restart{
    padding: 20px;
    font-size: 20px;
    background-color: yellow;
    border: none;
    border-radius: 10px;
    margin-top: 10px;
}

#gameBoard{
    background-color: tomato;
    max-width: 700px;
    display: grid;
}

Eu não tenho como ajudar, porque de fato, eu não sei aonde errei.

Obrigado pela atenção, Guilherme Ribeiro Tavares

2 respostas

No caso dos javascript, dividi em dois codigos :

let game = {
    lockMode: false,
    firstCard: null,
    secondCard: null,

    setCard: function (id) {
        let card = this.cards.filter(card => card.id === id)[0];
        console.log(card);
        if (card.flipped || this.lockMode) {
            return false;
        }

        if (!this.firstCard) {
            this.firstCard = card;
            this.firstCard.flipped = true;
            return true;
        } else {
            this.secondCard = card;
            this.secondCard.flipped = true;
            this.lockMode = true;
            return true;
        }
    },

    checkMatch: function () {
        if (!this.firstCard || !this.secondCard) {
            return false;
        }
        return this.firstCard.icon === this.secondCard.icon;
    },

    clearCards: function () {
        this.firstCard = null;
        this.secondCard = null;
        this.lockMode = false;
    },

    unflipCards: function () {
        this.firstCard.flipped = false;
        this.secondCard.flipped = false;
        this.clearCards();
    },

    checkGameOver: function () {
        return this.cards.filter(card => !card.flipped).length == 0;
    },

    techs: ['bootstrap', 'css', 'electron', 'firebase', 'html', 'javascript', 'jquery', 'mongo', 'node', 'react'],

    cards: null,

    createCardsFromTechs: function () {
        this.cards = [];
        this.techs.forEach((tech) => {
            this.cards.push(this.createPairFromTech(tech));
        });
        this.cards = this.cards.flatMap(pair => pair);
        this.shuffleCards();
        return this.cards;
    },

    createPairFromTech: function (tech) {
        return [{
            id: this.createIdWithTech(tech),
            icon: tech,
            flipped: false,
        }, {
            id: this.createIdWithTech(tech),
            icon: tech,
            flipped: false,
        }];
    },

    createIdWithTech: function (tech) {
        return tech + parseInt(Math.random() * 1000);
    },

    shuffleCards: function () {
        let currentIndex = this.cards.length;
        let randomIndex = 0;
        while (currentIndex !== 0) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex--;
            [this.cards[randomIndex], this.cards[currentIndex]] = [this.cards[currentIndex], this.cards[randomIndex]];
        }
    }
};

E por ultimo, o script.js:

const FRONT = "card_front";
const BACK = "card_back";
const CARD = "card";
const ICON = "icon";

startGame();

function startGame() {
    initializeCards(game.createCardsFromTechs());
}

function initializeCards(cards) {
    let gameBoard = document.getElementById("gameBoard");
    gameBoard.innerHTML = '';
    cards.forEach(card => {
        let cardElement = document.createElement('div');
        cardElement.id = card.id;
        cardElement.classList.add(CARD);
        cardElement.dataset.icon = card.icon;

        createCardContent(card, cardElement);

        cardElement.addEventListener('click', flipCard);
        gameBoard.appendChild(cardElement);
    });
}

function createCardContent(card, cardElement) {
    createCardFace(FRONT, card, cardElement);
    createCardFace(BACK, card, cardElement);
}

function createCardFace(face, card, element) {
    let cardElementFace = document.createElement('div');
    cardElementFace.classList.add(face);
    if (face === FRONT) {
        let iconElement = document.createElement('img');
        iconElement.classList.add(ICON);
        iconElement.src = "./assets/images/" + card.icon + ".png";
        cardElementFace.appendChild(iconElement);
    } else {
        cardElementFace.innerHTML = "&lt;/&gt;";
    }
    element.appendChild(cardElementFace);
}

function flipCard() {
    if (game.setCard(this.id)) {
        this.classList.add("flip");
        if (game.secondCard) {
            if (game.checkMatch()) {
                game.clearCards();
                if (game.checkGameOver()) {
                    let gameOverLayer = document.getElementById("gameOver");
                    gameOverLayer.style.display = 'flex';
                }
            } else {
                setTimeout(() => {
                    let firstCardView = document.getElementById(game.firstCard.id);
                    let secondCardView = document.getElementById(game.secondCard.id);

                    firstCardView.classList.remove('flip');
                    secondCardView.classList.remove('flip');
                    game.unflipCards();
                }, 1000);
            }
        }
    }
}

function restart() {
    game.clearCards();
    startGame();
    let gameOverLayer = document.getElementById("gameOver");
    gameOverLayer.style.display = 'none';
}
solução!

Oii Guilherme, tudo bem?

No console do navegador, há erros de carregamento de scripts?

Pra te ajudar, peço que você coloque o seu projeto em um repositório do GitHub, assim posso testar melhor e entender como você organizou as pastas e verificar se não é erro de importação.

Um abraço.