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.

            
                    label {
          margin: 0;
      }
      input[type=text] {
          width: 100%;
          padding: 6px 10px;
          margin: 8px 0;
          display: inline-block;
          border: 1px solid #ccc;
          border-radius: 4px;
          box-sizing: border-box;
      }
      input[type=submit] {
          width: 100%;
          background-color: #4CAF50;
          color: white;
          padding: 14px 20px;
          margin: 16px 0;
          border: none;
          border-radius: 4px;
          cursor: pointer;
      }
      input[type=submit]:hover {
          background-color: #45a049;
      }
      #signinDiv {
          display:inline-block;
          vertical-align:top;
          border-radius: 5px;
          background-color: #f2f2f2;
          padding: 20px;
          width: 425px;
          height: 600px;
          top: 0px;
      }
            
          
!
            
              (function () {
//function GoApp() {
  'use strict';

  const bot = new Bot({onRx:Receive});
  const tx = bot.tx;
  bot.sendMsg = bot.sendMessage;

var commandPoll = setInterval(commandCheck, 83);

var owner = [
  "83735214", //Paul
    "1070", //Maverick
  "225248065" //TOM2
];
var done = false;
//var timer = new Date().getTime();

function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

var cmTiles;
var socket;

var cmTile = {
  69 : "https://i.imgur.com/iXQkDid.png",
  0 : "https://i.imgur.com/ZqVVuNT.png",
  1 : "https://i.imgur.com/3zBrGbJ.png",
  2 : "https://i.imgur.com/iIyH1zf.png",
  3 : "https://i.imgur.com/sqTsYxB.png",
  4 : "https://i.imgur.com/IS6UKzK.png",
  5 : "https://i.imgur.com/eJY0wEn.png",
  6 : "https://i.imgur.com/2IFneiQ.png",
  7 : "https://i.imgur.com/B5FuwFS.png",
  8 : "https://i.imgur.com/Hutm5HY.png",
  9 : "https://i.imgur.com/vTfU8da.png",
  10 : "https://i.imgur.com/gFwd6be.png",
  11 : "https://i.imgur.com/Lv2D05X.png",
  12 : "https://i.imgur.com/ihaPFVA.png",
  13 : "https://i.imgur.com/zefmxDC.png",
  14 : "https://i.imgur.com/IyDlF6w.png"
}

var elements = [
];
var commands = [
];
var regNames = {
};
var cmCardLock = [
];
var cmLast = {
};
var cmScore = {
};
var cmParts = [
];
var cmPicks = [
];

var cmReady = false;
var cmProgress = 0;
var cmRound = 0;
var cmComp = false;

var commandsReady = true;
var commandDelay = [25, 0, 0];

Array.prototype.indexOfMax = function () {
    if (this.length === 0)
        return -1;

    var max = this[0];
    var maxIndex = 0;

    for (var i = 1; i < this.length; i++) {
        if (this[i] > max) {
            maxIndex = i;
            max = this[i];
        }
    }

    return maxIndex;
}

Array.prototype.indexOfMin = function () {
    if (this.length === 0)
        return -1;

    var min = this[0];
    var minIndex = 0;

    for (var i = 1; i < this.length; i++) {
        if (this[i] < min) {
            minIndex = i;
            min = this[i];
        }
    }

    return minIndex;
}

Array.prototype.picks = function(){
  if(this.length === 0 || this.length < 2)
    return -1;
  
  shuffle(this);
  
  var playerA = this.shift();
  var playerB = this.shift();
  
  return [playerA, playerB];
}


function sendCommand(obj){
  commands.push(obj); // simples

  // let str = JSON.stringify(obj);
  // let ej = LZString.compressToBase64(str);
  
  // commands.push(ej);
}


function doCommands(message, uid){
  var cc = message.charAt(0);
  if(!message || !uid || !done || cc != "!")
    return;
  if(owner.indexOf(uid) == -1)
    return;
  
  var argu = message.substring(1, message.length);
  var args = argu.split(" ");
  
  //console.log("Data: " + message, "ID: " + uid, "Command: " + args[0], "Args: " + args.slice(1, -1));
  
  args[0] = args[0].toLowerCase();
  switch(args[0]){
    case "cardmatch":
      if(!args[1])
        return;
      switch(args[1].toLowerCase()){
        case "list":
          var cMsg = "Users currently participating: ";
          if(cmParts.length == 0)
            cMsg += "None";
          for(var i = 0; cmParts.length > i; i++){
            if(regNames[cmParts[i]][0]){
              cMsg += regNames[cmParts[i]][1];
            }else{
              cMsg += cmParts[i];
            }
            if(i < (cmParts.length - 1))
              cMsg += ", ";
          }
          cMsg += ".";
          bot.sendMsg(cMsg);
        break;
        case "remove":
        case "uninvite":
          args[2] = args[2].toLowerCase();
          if(Array.isArray(regNames[args[2]])){
            if(cmParts.indexOf(args[2]) == -1)
              return bot.sendMsg("This user isn&apos;t participating in the competition.");
            cmParts.splice(cmParts.indexOf(args[2]), 1);
            bot.sendMsg("Removed the user with the id " + args[2] + " from current participants.");
          }else if(regNames[args[2]]){
            if(cmParts.indexOf(regNames[args[2]]) == -1)
              return bot.sendMsg("This user isn&apos;t participating in the competition.");
            cmParts.splice(cmParts.indexOf(regNames[args[2]]), 1);
            bot.sendMsg("Removed the user " + args[2] + " from current participants.");
          }else{
            bot.sendMsg("Failed to remove the user &quot;" + args[2] + "&quot; from current participants.");
          }
          
        break;
        case "add":
        case "invite":
          args[2] = args[2].toLowerCase();

          regNames = {}; // Translate to Mav whacky system
          for(let id in bot.users)
          {
            let isRegistered = !!bot.users[id].regname;
            regNames[''+id] = [isRegistered, isRegistered ? bot.users[id].regname : undefined];
            if(isRegistered)
              regNames[bot.users[id].regname.toLowerCase()] = ''+id;
          }
          
          if(Object.keys(regNames).indexOf(args[2]) != -1){
            if(Array.isArray(regNames[args[2]])){
              if(cmParts.indexOf(args[2]) != -1)
                return bot.sendMsg("The user with the id " + args[2] + " is already participating in the competition.");
              cmParts.push(args[2]);
              bot.sendMsg("The user with the id " + args[2] + " is now participating in the competition.");
            }else{
              if(cmParts.indexOf(regNames[args[2]]) != -1)
                return bot.sendMsg("The user " + args[2] + " is already participating in the competition.");
              cmParts.push(regNames[args[2]]);
              bot.sendMsg("The user " + args[2] + " is now participating in the competition.");
            }
          }else{
            bot.sendMsg("The user you're trying to invite is either invalid or has not joined this chatroom.");
          }
        break;
        case "start":
          if(((cmParts.length % 2 != 0) /*&& cmParts.length != 1*/) || cmParts.length == 0){
            bot.sendMsg("The amount of participants is zero or isn&apos;t divisible by 2.");
            return;
          }
          if(cmParts.length > 2)
            cmComp = true;
          cmRound = cmParts.length - 1;
          if(cmReady){
            clearElements(null, cardmatch);
          }else{
            cardmatch();
          }
        break;
        case "end":
          cmParts = [];
          clearElements();
          cmReady = false;
          cmComp = false;
        break;
      }
    break;
    case "clear":
      clearElements();
    break;
    case "sendbuff":
      sendCommand({
        streamGame: true,
        endStream: false,
        gameData: args.slice(1).join(" ").replace(/quot/g,"\"").replace(/apos/g, "'").replace(/[^a-zA-Z0-9\s\.\(\)\[\]\;\"\'\,]/g, "")
      });
    break;
    case "endbuff":
      sendCommand({
        streamGame: true,
        endStream: true,
        gameData: ""
      });
    break;
  }
}

function clearElements(i, callback){
  if(!i)
    i = 0;
  if(elements.length == i){
    elements = [];
    if(callback)
      return callback();
    return;
  }
  
  sendCommand({
    name: elements[i], 
    destroy: true 
  });
  
  i++;
  
  return setTimeout(clearElements, 50, i, callback);
}

function deleteElement(elementName){
  if(elements.indexOf(elementName) == -1)
    return;
  
  var elementIndex = elements.indexOf(elementName);
  elements.splice(elementIndex, 1);
  
  sendCommand({
    name: elementName, 
    destroy: true 
  });
}

function commandCheck(){
  if(commands.length > 0 && commandsReady)
    return commandQueue();
}

function commandQueue(i){
  tx(0, commands); // send lots of commands to all, simples ;)
  commands = []; // clear queue
  return;
  /*
  not needed ..
  
  if(commands.length == 0)
    return (commandsReady = true);
  if(!i)
    i = 0;
  
  var command = commands.shift();
  
  setTimeout(function(command, i){
    bot.sendCanvas(command);
    return commandQueue(i);
  }, commandDelay[2] > 0 ? commandDelay[0] + commandDelay[1] : commandDelay[0], command, i);
  
  return (commandDelay[2] = commandDelay[2] > 0 ? commandDelay[2] - 1 : commandDelay[2]);
  */
}

function cmCardset(tileName, tileIndex, tileX, tileY){
  //cm_commands.push(cm_cardset(decoy, "card_#{ctr[0]}_#{ctr[1]}", ctr[0] * 85, ctr[1] * 100))
  elements.push(tileName);
  
  //console.log(tileName);
  
  sendCommand({
    name: tileName,
    type: "Sprite",
    imageUrl: cmTile[tileIndex],
    anchor: {
      x: 0,
      y: 0
    },
    x: tileX,
    y: tileY,
    alpha: 1,
    height: 100,
    width: 85,
    interactive: true,
    buttonMode: true
  });
}


function cmBackground(url){
  elements.push("background");
  
  sendCommand({
    name: "background",
    type: "Sprite",
    imageUrl: url,
    anchor: {
      x: 0,
      y: 0
    },
    width: 425,
    height: 600
  });
}

function cmGenerate(){
  cmTiles = [
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]
  ];
  var cmGen = [];
  
  for(var i = 0; 30 > i; i++)
    cmGen.push(i % 15);
  
  shuffle(cmGen);

  for(var i = 0; cmTiles.length > i; i++){
    cmTiles[i] = cmGen.slice(0, 5);
    cmGen = cmGen.slice(5);
  }
}

function cardmatch() {

  cmGenerate();
  cmCardLock = [];
  cmProgress = 0;
  cmLast = {};
  cmScore = {};
  cmPicks = [];
  var rMsg = "";
  
  //if(cmParts.length == 1)
  //  cmPicks.push(cmParts.shift());
  cmPicks = cmParts.picks();
  cmRound -= 1; //3 -> 1 winner, 2 left, 2-> 2 winner, 1 left
  rMsg += "Starting the cardmatch round with the following picks: ";
  rMsg += (regNames[cmPicks[0]][0]) ? regNames[cmPicks[0]][1] + "(" + cmPicks[0] + "), " : cmPicks[0] + ", ";
  rMsg += (regNames[cmPicks[1]][0]) ? regNames[cmPicks[1]][1] + "(" + cmPicks[1] + ")." : cmPicks[1] + ".";
  
  bot.sendMsg(rMsg);
  
  //Allocate scores no matter what.
  for(var i = 0; cmPicks.length > i; i++)
    cmScore[cmPicks[i]] = 0;
  
  //console.log(cmScore, -8);

  cmBackground("https://i.imgur.com/xirFnNd.png");
  
  var ctr = [0, 0];
  for(var i = 0; cmTiles.length > i; i++){
    for(var j = 0; cmTiles[i].length > j; j++){
      cmCardset("card_" + ctr.join("_"), 69, ctr[0] * 85, ctr[1] * 100);
      ctr[0] += 1;
    }
    ctr = [0, ctr[1] + 1];
  }
  
  cmReady = true;
  
  //End
}

//codepen entry point, called when bot is set up
function main() {   
  done = true;
  let test = false;
  if(bot.dummys) // Are we in test mode
  {
    for(let id in bot.dummys)
    {
      doCommands("!cardmatch invite "+bot.users[id].regname, "1070"); // fake a start
      test = true;
    }
    if(test)
      doCommands("!cardmatch start", "1070"); // fake a start
  }
}

// Messages from players
function Receive(uid, pixi) {
  if(pixi.action == 'main')
  {
    main();
    return;
  }

  uid = ''+uid; // convert to string to keep indexof stuff working

  if(pixi.action == 'message')
  {
    doCommands(pixi.elements.t, uid);
    return;
  }


// function cmMain(pixi, packet){
//   if(!cmReady || !pixi || !pixi.name || !(packet && packet.elements.i && packet.elements.u))
//     return;
  
//   var uid = packet.elements.u;

  //Spectators may not play the game.
  if(cmPicks.indexOf(uid) == -1)
    return;
  
  switch(pixi.name.substr(0, 4)){
    case "card":
    case "tile":
      if(pixi.action == "click"){
        var cardCoord = pixi.name.substr(5, pixi.name.length).split("_");
        var card = cmTiles[cardCoord[1]][cardCoord[0]];
        
        //Card locking
        var cmCardIndex = cmCardLock.indexOf(cardCoord[0] + "_" + cardCoord[1]);
        if((cmCardIndex != -1) && (cmProgress < 14))
          return;
        cmCardLock.push(cardCoord[0] + "_" + cardCoord[1]);
        
        //Remove old tile
        deleteElement("card_" + cardCoord.join("_"));
        
        cmCardset("tile_" + cardCoord.join("_"), card, cardCoord[0] * 85, cardCoord[1] * 100);
        
        if(Object.keys(cmLast).indexOf(uid) == -1)
          cmLast[uid] = [];
        cmLast[uid].push({
          "card": parseInt(card),
          "x": parseInt(cardCoord[0]),
          "y": parseInt(cardCoord[1])
        });
        
        if(cmLast[uid].length == 2){
          
          var cardA = cmLast[uid][0];
          var cardB = cmLast[uid][1];
          
          if((cardA["card"] == cardB["card"]) && (cardA != cardB) && ((cardA["card"] != 69) && (cardB["card"] != 69))){
            if(Object.keys(cmScore).indexOf(uid) == -1)
              cmScore[uid] = 0;

            cmScore[uid] += 1;
            cmProgress += 1;
            
            setTimeout(function(){
              deleteElement("tile_" + cardA["x"] + "_" + cardA["y"]);
              deleteElement("tile_" + cardB["x"] + "_" + cardB["y"]);
            },250);
          }else{
            setTimeout(function(cardA, cardB){
              deleteElement("tile_" + cardA["x"] + "_" + cardA["y"]);
              deleteElement("tile_" + cardB["x"] + "_" + cardB["y"]);
              cmCardset("card_" + cardA["x"] + "_" + cardA["y"], 69, cardA["x"] * 85, cardA["y"] * 100);
              cmCardset("card_" + cardB["x"] + "_" + cardB["y"], 69, cardB["x"] * 85, cardB["y"] * 100);
              
              //Desync Fix?
              var cardAIndex = cmCardLock.indexOf(cardA["x"] + "_" + cardA["y"]);
              cmCardLock.splice(cardAIndex, 1);
              var cardBIndex = cmCardLock.indexOf(cardB["x"] + "_" + cardB["y"]);
              cmCardLock.splice(cardBIndex, 1);
            }, 1000, cardA, cardB);
          }
          
          cmLast[uid] = [];
          //var cardAIndex = cmCardLock.indexOf(cardA["x"] + "_" + cardA["y"]);
          //cmCardLock.splice(cardAIndex, 1);
          //var cardBIndex = cmCardLock.indexOf(cardB["x"] + "_" + cardB["y"]);
          //cmCardLock.splice(cardBIndex, 1);
        }
        
        if(cmProgress == 15){
          cmReady = false;

          var cMsg = "";
          var compWinner;
          
          if(cmPicks.length == 2){
            var matches = [];
            compWinner = (cmRound == 0);
            
            for(var i = 0; Object.keys(cmScore).length > i; i++)
              matches.push(cmScore[Object.keys(cmScore)[i]]);
            var winner = [matches[matches.indexOfMax()], Object.keys(cmScore)[matches.indexOfMax()]];
            var loser = [matches[matches.indexOfMin()], Object.keys(cmScore)[matches.indexOfMin()]];
            //console.log(matches, cmScore, matches.indexOfMax(), matches.indexOfMin(), -9);
            
            //Remove losers
            cmParts.splice(loser[1], 1);
            if(!compWinner)
              cmParts.push(winner[1]);
            
            if(regNames[winner[1]][0]){
              cMsg += regNames[winner[1]][1] + "(" + winner[1] + ") won" + ((compWinner && cmComp) ? " the competition " : " ") +"with " + (winner[0] == 0 ? "no" : winner[0]) + " match" + ((winner[0] > 1 || winner[0] == 0) ? "es" : "") + ", and ";
            }else{
              cMsg += winner[1] + " won" + ((compWinner && cmComp) ? " the competition " : " ") + "with " + (winner[0] == 0 ? "no" : winner[0]) + " match" + ((winner[0] > 1 || winner[0] == 0) ? "es" : "") + ", and ";
            }
            
            if(regNames[loser[1]][0]){
              cMsg += regNames[loser[1]][1] + "(" + loser[1] + ") lost with " + ((loser[0] == 0) ? "no" : loser[0]) + " match" + ((loser[0] > 1 || loser[0] == 0) ? "es" : "") + ", and has dropped out.";
            }else{
              cMsg += loser[1] + " lost with " + ((loser[0] == 0) ? "no" : loser[0]) + " match" + ((loser[0] > 1 || loser[0] == 0) ? "es" : "") + ", and has dropped out.";
            }
            
            
          }
          
          /*else if(cmPicks.length == 1){
            //
          }else{
            //
          }*/
          
          bot.sendMsg(cMsg);
          
          cmCardLock = [];
          cmLast = {};
          cmScore = {};
          cmProgress = 0;
          cmPicks = [];
          setTimeout(clearElements, 1000);
          
          if(!compWinner)
            return setTimeout(cardmatch, 4000);
          if(compWinner){
            if(cmComp)
              bot.sendMsg("The cardmatch competition has ended.");
            cmComp = false;
            cmParts = [];
          }
          
          //uid = matches = winnerPos = winnerMsg = null;
        }
      }
    break;
  }
  
  //console.log(pixi, packet);
}

// const bot = new Bot();
// bot.login();
//bot.sendMsg("Hello world");

})();
            
          
!
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