123

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.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="screen screen--intro">
  <div class="textbox">
    <p>Welcome to my little game of memo! It's build as a object-oriented JavaScript state machine. Images come from FontAwesome.</p>
    <p class="center"><a class="textbox__button introbox__button" href="#screen--table">Play</a></p>
  </div>
</div>
<div class="screen screen--table">
  <div class="l_cards">
  </div>
  <div class="moves">
    0
  </div>
  
  <!-- score counter -->
  <!-- place cards ~pleasingly~ in the middle of the table. "divisible by x"? -->
</div>
<div class="screen screen--end">
  <div class="textbox">
    <p>Hurrah! You won! You finished the game in <strong class="final-move-count"></strong> moves.</p>
    <p class="center"><a class="textbox__button endbox__button" href="#screen--table">Play again</a></p>
  </div>
</div>
            
          
!
            
                html,body {
  height:100%;
  margin:0;
}

body {
  font-family:Arial, sans-serif;
  line-height:1.5em;
}

.screen {
  display:none;
  width:100%;
  height:100%;
  min-height:100%;/*for mozilla*/
  
}

.screen--active {
  display:flex;
}

.screen--intro,
.screen--end{
  background-color:#7CB342;
  align-items:center;
  justify-content:center;
}

.textbox {
  background-color:#ffffff;
  width:30em;
  margin:auto;
  padding:1em;
  border-radius:0.2em;
}

.textbox__button {
  display:inline-block;
  text-align:center;
  background-color:#7CB342;
  width:auto;
  padding:0.4em;
  color:#ffffff;
  text-decoration:none;
  border-radius:0.2em;
}
.textbox__button:hover,
.textbox__button:focus {
  color:#004D40;
}

.screen--table {
  align-items:center;
  justify-content:center;
  align-content:center;
}

.l_cards {
  display: flex;
  flex-wrap:wrap;
  align-content:center;
  align-items:left;
  justify-content:left;
  width: 90%;
  max-width: 40em;
  height: 90%;
  margin: 0 auto;
}

.card {
  font-size:100%;
  background-color:#7CB342;
  color:#004D40;
  border-radius:0.2em;
  text-align:center;
  color:white;
  display:flex;
  align-items:center;
  justify-content:center;
}

.card i {
  
}

p.center {
  text-align:center;
}

.moves {
  position:absolute;
  top:0;
  left:0;
  background-color:#7CB342;
  padding:0.5em;
  color:#fff;
}
            
          
!
            
              const cardImages = ['ambulance',
'anchor',
'archive',
'award',
'balance-scale',
'bath',
'bed',
'beer',
'bell',
'bell',
'bicycle',
'binoculars',
'birthday-cake',
'blender',
'bomb',
'book',
'bookmark',
'briefcase',
'broadcast-tower',
'bug',
'building',
'bullhorn',
'bullseye',
'bus',
'calculator',
'calendar',
'calendar-alt',
'camera',
'camera-retro',
'car',
'church',
'clipboard',
'cloud',
'coffee',
'cog',
'cogs',
'compass',
'cookie',
'cookie-bite',
'copy',
'crow',
'cube',
'cubes',
'cut',
'dice',
'dice-five',
'dice-four',
'dice-one',
'dice-six',
'dice-three',
'dice-two',
'digital-tachograph',
'door-closed',
'door-open',
'dove',
'drum',
'drum-steelpan',
'envelope',
'envelope-open',
'eraser',
'eye',
'eye-dropper',
'fax',
'feather',
'feather-alt',
'fighter-jet',
'file',
'file-alt',
'file-prescription',
'film',
'fire',
'fire-extinguisher',
'fish',
'flag',
'flag-checkered',
'flask',
'frog',
'futbol',
'gamepad',
'gavel',
'gem',
'gift',
'glass-martini',
'glasses',
'globe',
'graduation-cap',
'hdd',
'headphones',
'headphones-alt',
'headset',
'heart',
'helicopter',
'highlighter',
'home',
'hospital',
'hourglass',
'image',
'images',
'industry',
'key',
'keyboard',
'kiwi-bird',
'laptop',
'leaf',
'lemon',
'life-ring',
'lightbulb',
'lock',
'lock-open',
'magic',
'magnet',
'map',
'map-marker',
'map-marker-alt',
'map-pin',
'map-signs',
'marker',
'medal',
'medkit',
'memory',
'microchip',
'microphone',
'microphone-alt',
'mobile',
'mobile-alt',
'money-bill',
'money-bill-alt',
'money-check',
'money-check-alt',
'moon',
'motorcycle',
'newspaper',
'paint-brush',
'paper-plane',
'paperclip',
'paste',
'paw',
'pen',
'pen-alt',
'pen-fancy',
'pen-nib',
'pencil-alt',
'phone',
'plane',
'plug',
'print',
'puzzle-piece',
'road',
'rocket',
'ruler-combined',
'ruler-horizontal',
'ruler-vertical',
'save',
'school',
'screwdriver',
'search',
'shield-alt',
'shopping-bag',
'shopping-basket',
'shopping-cart',
'shower',
'snowflake',
'space-shuttle',
'star',
'sticky-note',
'stopwatch',
'subway',
'suitcase',
'sun',
'tablet',
'tablet-alt',
'tachometer-alt',
'tag',
'tags',
'taxi',
'thumbtack',
'ticket-alt',
'toolbox',
'train',
'trash',
'trash-alt',
'tree',
'trophy',
'truck',
'tv',
'umbrella',
'university',
'unlock',
'unlock-alt',
'utensil-spoon',
'utensils',
'wallet',
'weight',
'wheelchair',
'wine-glass',
'wrench'
];

const cardSizing = {
  width:3,
  height:4,
  margin:0.1
}

class Card {
  constructor(symbol,parent,color) {
    this.symbol = symbol;
    this.parent = parent;
    this.color = color;
    this.backColor = '#c0c0cc';
    this.flipped = false;
    this.element = document.createElement('div');
    this.element.style.width= cardSizing.width +"em";
    this.element.style.height = cardSizing.height + "em";
    this.element.style.margin = cardSizing.margin + "em";
    this.element.classList.add("card");    
  }  
  draw() {
    this.parent.appendChild(this.element);
   this.flipBack(); 
  }
  
  flipFront() {
    console.log("image: "+this.symbol);
    this.flipped = true;
    this.element.innerHTML = `<i class="fas fa-${this.symbol}"></i></div>`;
    console.log("color: "+this.color);
    this.element.style.backgroundColor = this.color;
    this.element.removeEventListener('click',this);
  }
  flipBack() {
    this.flipped = false;
    this.element.innerHTML = `<i class="fas fa-stroopwafel"></i></div>`;
    this.element.style.backgroundColor = this.backColor;
    this.element.addEventListener('click',this); //I really like this trick: you can pass an object with a method handleEvent(event) instead of a named/anonymous function. It dramatically simplifies scoping! Cred: https://medium.com/@photokandy/til-you-can-pass-an-object-instead-of-a-function-to-addeventlistener-7838a3c4ec62
  }
  remove() {
    this.element.style.visibility = 'hidden';
  }
  handleEvent(event) {
    if (event.type == 'click') {
      game.increaseCounter();
      game.dispatch('cardClick',this);
    }
  }
}
      //I'm working from this design: https://www.smashingmagazine.com/2018/01/rise-state-machines/
const game = {
  cardCount:10,
  images:cardImages,
  cards:[],
  cardsLeft:0,
  moves:0,
  firstCard:null,
  secondCard:null,
  state:null,
  screen:null,
  increaseCounter() {
    this.moves++;
    this.moveCounter.innerHTML = this.moves;
  },
  resetGameValues() {
    this.cards = [];
    this.cardsLeft = this.cardCount;
    this.moves = 0;
    this.firstCard = null;
    this.secondCard = null;
  },
  dispatch(actionName, ...payload) {
    const actions = this.states[this.state];
    const action = this.states[this.state][actionName];
    
    if (action) {
      action.apply(game, payload);
    }
  },
  changeStateTo(newState) {
    this.state = newState;
  },
  setScreenTo(newScreen) {
    if (this.screen != null) {
      document.getElementsByClassName('screen--'+this.screen)[0].classList.remove('screen--active');
    }    
    document.getElementsByClassName('screen--'+newScreen)[0].classList.add('screen--active');
    this.screen = newScreen;
  },
  states:{
    'init':{
      setup:function() {
        console.log("setting up the game");
        this.setScreenTo('intro');
        this.changeStateTo('intro');
        document.getElementsByClassName('introbox__button')[0].addEventListener('click',function(event) {
          game.dispatch('click');
        });
      }
    },
    'intro':{
      click:function(){
        console.log("transition: dealing");
        this.setScreenTo('table');
        this.resetGameValues();
        let cards = document.getElementsByClassName("l_cards")[0];
        while (cards.firstChild) {
          cards.removeChild(cards.firstChild)
        };
        
        let area = (cardSizing.width+cardSizing.margin)*(cardSizing.height+cardSizing.margin)*this.cardCount*2;
        cards.style.maxWidth = Math.ceil(Math.sqrt(area))+"em";
        
        let symbolsFound = 0;
        let color = [0,80,40];
        let imgLength = this.images.length;
        let randObj = {};
        while (symbolsFound<this.cardCount) {
          let ind = Math.floor(imgLength*Math.random());
          if(randObj[ind]) {
            continue;
          } else {
            randObj[ind] = true;
            symbolsFound++;
          }
        }        
        let symbolIndexes = Object.keys(randObj);
        for (let i=0;i<symbolsFound;i++) {
          color[0] = Math.floor(Math.random()*360);
          let colorHSL = 'hsl('+color[0]+','+color[1]+'%,'+color[2]+'%)'; //the first value of HSL is an angle -> no percent sign!
          this.cards.push(new Card(this.images[symbolIndexes[i]],cards,colorHSL)); //first
          this.cards.push(new Card(this.images[symbolIndexes[i]],cards,colorHSL)); //second  
        };
        
        //randomize the cards using Durstenfeld shuffle algorythm (props: https://stackoverflow.com/a/12646864)
        for (let i = this.cards.length - 1;i > 0;i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [this.cards[i],this.cards[j]] = [this.cards[j],this.cards[i]];
        }
        this.cards.forEach(function(item,index,array){item.draw();});
        this.moveCounter = document.getElementsByClassName("moves")[0];
        this.moveCounter.innerHTML = this.moves;
        this.changeStateTo('idle');
      }
    },
    'idle':{
      cardClick:function(card){
        console.log("transition: flip1st");
        card.flipFront();
        this.firstCard = card;
        this.changeStateTo('oneCardFlipped');
      },
      finish:function(){
        console.log("transition:finish");
        let finalMoveCount = document.getElementsByClassName('final-move-count')[0];
        finalMoveCount.innerHTML = this.moves;
        this.setScreenTo('end');
        this.changeStateTo('end');
        document.getElementsByClassName('endbox__button')[0].addEventListener('click',function(event) {
          game.dispatch('click');
        });
      }
    },
    'oneCardFlipped':{
      cardClick:function(card){
        console.log("transition: flip2nd");
        this.secondCard = card;
        this.secondCard.flipFront();
        this.changeStateTo('matching');
        game.dispatch('matchCards');
      }
    },
    'matching':{
      'matchCards':function(){
        console.log("state: matching cards");
        window.setTimeout(function(){
          if (this.firstCard.symbol == this.secondCard.symbol) {
            console.log("yes!");
            this.firstCard.remove();
            this.secondCard.remove();
            this.firstCard = null;
            this.secondCard = null;
            this.cardsLeft--;
            this.changeStateTo('idle');
            console.log(this.cardsLeft);
            if (this.cardsLeft == 0) {
              console.log("no cards left");
              game.dispatch('finish');
            }
          } else {
            console.log("no");
            this.firstCard.flipBack();
            this.secondCard.flipBack();
            this.firstCard = null;
            this.secondCard = null;
            this.changeStateTo('idle');
          }          
        }.bind(this),1000); 
      }    
    },
    'end':{
      click:function(){
        console.log("transition: reset");
        this.changeStateTo('intro');
        game.dispatch("click");
      }
    },
      
  }
}
/*
State machines consist of STATES and TRANSITIONS. States are stable and wait for input, transitions process data and then switch to a state. EVENTS are what triggers transitions.

In this game, there are these STATES: 
* init - initial game state
* intro - intro text; waiting for button click
* idle -- waits for a card to be flipped
* oneCardFlipped -- waits for 2nd card to be flipped
* end - score card and reset button

This game has these TRANSITIONS:
* setup - from init to intro, draws the first screen
* dealing - from intro to idle, cards being laid out
* flip1st - from idle to oneCardFlipped
* flip2nd - from oneCardFlipped to matching
* matching - matches the flipped cards and removes them or flips them back; if all cards are flipped, it triggers the finish transition
* finish - from oneCardFlipped to end; draws the end  screen
* reset - start a new game

*/

game.changeStateTo('init');
game.dispatch('setup');



            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console