cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

Quick-add: + add another resource

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <main>
    <header style="text-align: center;">
        <h1>Memory Games</h1>
    </header>

    <nav style="display: flex; flex-direction: row">
        <h2>Select a difficulty:</h2>
        <ul>
            <li>
                <button id="start-easy">Easy</button>
            </li>
            <li>
                <button id="start-medium">Medium</button>
            </li>
            <li>
                <button id="start-hard">Hard</button>
            </li>
        </ul>
    </nav>

    <section id="stage">

    </section>
</main>

<template id="card-template">
    <article class="card">
        <h2 data-value></h2>
    </article>
</template>

            
          
!
            
              #stage {
            display: flex;
        }

        .card {
            margin: 1rem;
            width: 10rem;
            height: 10rem;
        }

.card.selected {
            border: blue 2px solid;
            color: blue;
        }
            
          
!
            
              document.addEventListener('DOMContentLoaded', matchingGame);
        function matchingGame(){

            var startEasy = document.getElementById('start-easy');
            var startMedium = document.getElementById('start-medium');
            var startHard = document.getElementById('start-hard');

            var stage = document.getElementById('stage');

            var cardTemplate = document.getElementById('card-template');

            var totalCards;
            var renderedCards;

            var selectedCard;

            init();
            function init(){
                startEasy.addEventListener('click', initEasy);
                // startMedium.addEventListener('click', initMedium);
                // startHard.addEventListener('click', initHard);
                initEasy();
            }

            function initEasy(){
                totalCards = 4;// TODO random!
                renderedCards = 0;

                renderCards();
                bindCards();
                resetSelections();
            }

            function renderCards(){
                var documentFragments = document.createDocumentFragment();
                var cards = [];
                while(renderedCards < totalCards){
                    var number = getRandomInt(1, 100);
                    // Make two cards
                    var card = renderCard(number);
                    cards.push(card);
                    card = renderCard(number);
                    cards.push(card);
                    renderedCards += 2;
                }

                cards = shuffle(cards);
                cards.forEach(function(card){
                    documentFragments.appendChild(card);
                });

                stage.innerHTML = '';
                stage.appendChild(documentFragments);

                // TODO bind to the cards and listen for click. Leave the first card 'selected', when the second card is selected, test if htey match and remove them from the sets.
            }

            /**
             * @param {int} number
             * @return Node
             */
            function renderCard(number){
                var clone = document.importNode(cardTemplate.content, true);
                var element = clone.querySelector('[data-value]');
                element.dataset.value = number;
                element.innerHTML = number;
                return clone;
            }

            function bindCards(){
                Array.from(stage.querySelectorAll('.card')).forEach(function(card){
                    card.addEventListener('click', handleCardClick);
                })
            }

            /**
             * Resets if the game is beaten or not
             */
            function resetSelections(){
                selectedCard = undefined;
                Array.from(stage.querySelectorAll('.card.selected')).forEach(function(card){
                    card.classList.remove('selected');
                });
            }

            /**
             * @param {Event} event
             */
            function handleCardClick(event){
               if(!selectedCard){
                   console.log('First selection: ', event.currentTarget);
                   selectedCard = event.currentTarget;
                   selectedCard.classList.add('selected');
                   return;
               }


               console.log('second selection', selectedCard, event.currentTarget);

               // TODO was this first or second selection?
                // TODO how do you 'show' the user?
            }

            /**
             * Reorders an array
             * @param array
             * @returns {*}
             */
            function shuffle(array) {
                var currentIndex = array.length, temporaryValue, randomIndex;

                // While there remain elements to shuffle...
                while (0 !== currentIndex) {

                    // Pick a remaining element...
                    randomIndex = Math.floor(Math.random() * currentIndex);
                    currentIndex -= 1;

                    // And swap it with the current element.
                    temporaryValue = array[currentIndex];
                    array[currentIndex] = array[randomIndex];
                    array[randomIndex] = temporaryValue;
                }

                return array;
            }

            /**
             * Returns a random integer between min (inclusive) and max (inclusive)
             * Using Math.round() will give you a non-uniform distribution!
             */
            function getRandomInt(min, max) {
                return Math.floor(Math.random() * (max - min + 1)) + min;
            }

        }
            
          
!
999px
Loading ..................

Console