Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="app" class="min-h-screen flex flex-col items-center justify-center bg-gray-900 select-none">
  <h1 class="font-sans font-bold text-6xl text-blue-200 mb-4">2048</h1>
  <header class="flex space-x-4">
    <div class="w-48 bg-gray-800 p-4 my-4 rounded-lg font-sans text-center font-bold">
      <h4 class="text-sm text-gray-500 uppercase mb-1">score</h4>
      <span class="inline-block -mb-1 text-2xl text-gray-300" v-html="score"></span>
    </div>
    <div class="w-48 p-4 my-4 rounded-lg font-sans text-center font-bold" :class="newHighscore ? 'bg-blue-800 bg-gradient-to-b from-blue-700' : 'bg-gray-800'">
      <h4 class="text-sm uppercase mb-1" :class="newHighscore ? 'text-blue-300' : 'text-gray-500'">best</h4>
      <span class="inline-block -mb-1 text-2xl" :class="newHighscore ? 'text-blue-100' : 'text-gray-300'" v-html="bestScore"></span>
    </div>
  </header>
  <div class="relative">
    <div ref="container" class="container flex flex-wrap bg-gray-800 flex flex-wrap p-2 box-content rounded-lg shadow-lg">
      <div v-for="i in gridSize" :key="i" class="tile m-2 flex items-center justify-center rounded bg-gray-700 text-gray-100" :key="i"></div>
      <transition-group enter-active-class="transform" leave-active-class="transform" enter-from-class="opacity-0 scale-75" leave-to-class="opacity-0 scale-75">
        <div v-for="(tile, i) in tiles" :key="`tile_${tile.id}`" :ref="setItemRef.bind($event, tile.id)" class="tile absolute m-2 flex items-center justify-center rounded bg-gradient-to-b transition-all" :class="[bgColor(tile.value), `duration-${transitionDuration}`, tile.classes]" :style="setTilePosition(tile.position.x, tile.position.y)">
          <span class="font-sans font-bold text-2xl" v-html="tile.value"></span>
        </div>
      </transition-group>

    </div>
    <transition enter-active-class="transition-all duration-300" enter-from-class="opacity-0">
      <div v-if="gameOver" class="game-over absolute inset-0 flex flex-col items-center justify-center bg-gray-900 bg-opacity-75 rounded-lg">
        <h2 class="font-sans font-bold text-white text-4xl">Game over!</h2>
        <span class="mt-4 font-sans font-bold text-white text-2xl">{{score}}</span>
      </div>
    </transition>
  </div>
  <button class="mt-4 bg-blue-900 px-8 py-4 rounded-md font-sans font-bold uppercase text-sm text-blue-100 bg-gradient-to-b from-blue-800 hover:bg-blue-800 hover:from-blue-700 focus:outline-none" @click="startGame()">Restart Game</button>
</div>
              
            
!

CSS

              
                .container {
  width: 24rem;
  height: 24rem;
  .tile {
    width: 5rem;
    height: 5rem;
  }
}

.game-over {
  backdrop-filter: blur(8px);
}

              
            
!

JS

              
                const vueApp = {
  data() {
    return {
      disabledControls: false,
      transitionDuration: 300,
      highestId: 0,
      width: 4,
      startTiles: 2,
      tiles: [],
      score: 0,
      bestScore: 0,
      newHighscore: false,
      gameOver: true,
      won: false
    };
  },
  methods: {
    setItemRef(id, e) {
      if (id && e) {
        this.tiles.find((item) => item.id === id).item = e;
      }
    },
    generateRandomNum() {
      this.checkLose();
      if (this.tiles.length <= 15) {
        let randomPosX = Math.floor(Math.random() * this.width);
        let randomPosY = Math.floor(Math.random() * this.width);
        let randomNumber = Math.random() < 0.9 ? 2 : 4;

        let exists = false;
        for (let i = 0; i < this.tiles.length; i++) {
          if (
            this.tiles[i].position.x === randomPosX &&
            this.tiles[i].position.y === randomPosY
          ) {
            exists = true;
          }
        }
        if (!exists) {
          this.createTile(randomPosX, randomPosY, randomNumber)
        } else {
          this.generateRandomNum();
        }
      }
    },
    createTile(posX, posY, value) {
      this.highestId++;
      this.tiles.push({
        id: this.highestId,
        position: {
          x: posX,
          y: posY
        },
        value: value,
        item: null,
        classes: []
      });
      const newTile = this.tiles.find(tile => tile.id === this.highestId)
      newTile.classes.push('z-10')
      this.disabledControls = false;
      setTimeout(() => {
        newTile.classes.splice(0,1)
      }, this.transitionDuration);
    },
    control(e) {
      if (!this.disabledControls) {
        if (e.key === "ArrowRight" || e.detail.dir === "right") {
          this.disabledControls = true;
          this.goRight();
        } else if (e.key === "ArrowLeft" || e.detail.dir === "left") {
          this.disabledControls = true;
          this.goLeft();
        } else if (e.key === "ArrowUp" || e.detail.dir === "up") {
          this.disabledControls = true;
          this.goUp();
        } else if (e.key === "ArrowDown" || e.detail.dir === "down") {
          this.disabledControls = true; 
          this.goDown();
        }
      }
    },
    goUp() {
      for (let i = 0; i < this.width; i++) {
        let column = this.tiles.filter((item, itemIndex) => {
          return this.tiles[itemIndex].position.x === i;
        });
        if (column.length) {
          column = column.sort((a, b) => {
            return a.position.y > b.position.y ? 1 : a.position.y < b.position.y ? -1 : 0;
          });
        }
        this.combineUp(column);
      }
      setTimeout(() => this.generateRandomNum(), this.transitionDuration);
    },
    combineUp(column) {
      let filteredColumn = JSON.parse(JSON.stringify(column));
      for (let i = 0; i < filteredColumn.length - 1; i++) {
        let current = filteredColumn[i].value;
        let prev = filteredColumn[i + 1]?.value;

        if (prev === current) {
          filteredColumn[i].value = current + prev;
          filteredColumn[i].prevId = filteredColumn[i + 1].id;
          filteredColumn[i + 1].value = 0
        }
      }
      
      filteredColumn = filteredColumn.filter(e => e.value)
      let missing = this.width - filteredColumn.length;
      let zeros = Array(missing).fill({ value: 0 });
      filteredColumn = filteredColumn.concat(zeros);
      
      this.reposition(filteredColumn, 'column')
    },
    goDown() {
      for (let i = 0; i < this.width; i++) {
        let column = this.tiles.filter((item, itemIndex) => {
          return this.tiles[itemIndex].position.x === i;
        });
        if (column.length) {
          column = column.sort((a, b) => {
            return a.position.y > b.position.y ? 1 : a.position.y < b.position.y ? -1 : 0;
          });
        }
        this.combineDown(column);
      }
      setTimeout(() => this.generateRandomNum(), this.transitionDuration);
    },
    combineDown(column) {
      let filteredColumn = JSON.parse(JSON.stringify(column));
      for (let i = filteredColumn.length - 1; i >= 0; i--) {
        let current = filteredColumn[i].value;
        let prev = filteredColumn[i - 1]?.value;

        if (prev === current) {
          filteredColumn[i].value = current + prev;
          filteredColumn[i].prevId = filteredColumn[i - 1].id;
          filteredColumn[i - 1].value = 0
        }
      }
      
      filteredColumn = filteredColumn.filter(e => e.value)
      let missing = this.width - filteredColumn.length;
      let zeros = Array(missing).fill({ value: 0 });
      filteredColumn = zeros.concat(filteredColumn);
       
      this.reposition(filteredColumn, 'column')
    },
    goRight() {
      for (let i = 0; i < this.width; i++) {
        let row = this.tiles.filter((item, itemIndex) => {
          return this.tiles[itemIndex].position.y === i;
        });
        if (row.length) {
          row = row.sort((a, b) => {
            return a.position.x > b.position.x ? 1 : a.position.x < b.position.x ? -1 : 0;
          });
        }
        this.combineRight(row);
      }
      setTimeout(() => this.generateRandomNum(), this.transitionDuration);
    },
    combineRight(row) {
      let filteredRow = JSON.parse(JSON.stringify(row));
      for (let i = filteredRow.length - 1; i >= 0; i--) {
        let current = filteredRow[i].value;
        let prev = filteredRow[i - 1]?.value;

        if (prev === current) {
          filteredRow[i].value = current + prev;
          filteredRow[i].prevId = filteredRow[i - 1].id;
          filteredRow[i - 1].value = 0
        }
      }
      
      /*
        let values = filteredRow.filter(e => e.value)
        let empties = filteredRow.filter(e => e.value === 0)
        let combined = empties.concat(values)
        let missingFields = this.width - combined.length
        let emptyFields = Array(missingFields).fill({ value: 0 });
        combined = emptyFields.concat(combined)
        console.log(values, empties, combined)
        this.reposition(combined, 'row')
      */
      
      filteredRow = filteredRow.filter(e => e.value)
      let missing = this.width - filteredRow.length;
      let zeros = Array(missing).fill({ value: 0 });
      filteredRow = zeros.concat(filteredRow);
      this.reposition(filteredRow, 'row')
      
    },
    goLeft() {
      for (let i = 0; i < this.width; i++) {
        let row = this.tiles.filter((item, itemIndex) => {
          return this.tiles[itemIndex].position.y === i;
        });
        if (row.length) {
          row = row.sort((a, b) => {
            return a.position.x > b.position.x ? 1 : a.position.x < b.position.x ? -1 : 0;
          });
        }
        this.combineLeft(row);
      }
      setTimeout(() => this.generateRandomNum(), this.transitionDuration);
    },
    combineLeft(row) {
      let filteredRow = JSON.parse(JSON.stringify(row));
      for (let i = 0; i < filteredRow.length - 1; i++) {
        let current = filteredRow[i].value;
        let prev = filteredRow[i + 1]?.value;

        if (prev === current) {
          filteredRow[i].value = current + prev;
          filteredRow[i].prevId = filteredRow[i + 1].id;
          filteredRow[i + 1].value = 0
        }
      }
      
      filteredRow = filteredRow.filter(e => e.value)
      let missing = this.width - filteredRow.length;
      let zeros = Array(missing).fill({ value: 0 });
      filteredRow = filteredRow.concat(zeros);
      
      this.reposition(filteredRow, 'row')
    },
    reposition(array, position) {
      const pos = position === 'row' ? 'x' : 'y';
      for (let i = array.length - 1; i >= 0; i--) {
        if (array[i].value > 0) {
          const currentTile = this.tiles.find(tile => tile.id === array[i].id)
          const tileIndex = this.tiles.findIndex(tile => tile.id === array[i].id)
          const prevTile = array[i].prevId ? this.tiles.find(tile => tile.id === array[i].prevId) : null
          
          
          currentTile.position[pos] = i;
          currentTile.value = array[i].value;
          
          if (prevTile) {            
            currentTile.classes.push('z-10')
            prevTile.position[pos] = i;
            this.score += array[i].value;
            
            //console.log(array)
            //console.log(JSON.parse(JSON.stringify(this.tiles)))
            setTimeout(() => {
              /*const tileSettings = {
                position: {
                  x: currentTile.position.x,
                  y: currentTile.position.y
                },
                value: currentTile.value
              }*/
              //currentTile.classes.splice(0,1)
              this.tiles.splice(tileIndex, 1);
              const prevTileIndex = this.tiles.findIndex(tile => tile.id === array[i].prevId)
              this.tiles.splice(prevTileIndex, 1);

              this.createTile(currentTile.position.x, currentTile.position.y, currentTile.value);
              
            }, this.transitionDuration);
          }
        }
      }
    },
    easyTest(row) {
      row = row.filter(e => e);
      for (let i = row.length - 1; i >= 0; i--) {
        let current = row[i];
        let prev = row[i - 1];

        if (prev === current) {
          row[i] = current + prev;
          row[i - 1] = 0;
        }
      }

      row = row.filter(e => e);
      var missing = 4 - row.length;
      var zeros = Array(missing).fill(0);

      row = zeros.concat(row);

      return row;
    },
    checkWin() {
      if (this.tiles.some((i) => i.value === 2048)) {
        this.won = true;
      }
    },
    checkLose() {
      let noTilesAvaliable = (this.tiles.length >= 15);
      if (noTilesAvaliable) {
        setTimeout(() => (this.gameOver = true), this.transitionDuration);

        document.removeEventListener("keyup", this.control);
        document.removeEventListener("swiped", this.control);
      }
    },
    bgColor(val) {
      switch (val) {
        case 2:
          return "bg-gray-600 from-gray-500 text-gray-200";
        case 4:
          return "bg-indigo-200 from-indigo-100 text-indigo-700";
        case 8:
          return "bg-indigo-300 from-indigo-200 text-indigo-800";
        case 16:
          return "bg-purple-200 from-purple-100 text-purple-700";
        case 32:
          return "bg-purple-300 from-purple-200 text-purple-800";
        case 64:
          return "bg-purple-500 from-purple-400 text-purple-100";
        case 128:
          return "bg-orange-200 from-orange-100 text-orange-700";
        case 256:
          return "bg-orange-500 from-orange-400 text-orange-100";
        case 512:
          return "bg-orange-600 from-orange-500 text-orange-100";
        case 1024:
          return "bg-yellow-400 from-yellow-300 text-yellow-700";
        case 2048:
          return "bg-yellow-500 from-yellow-400 text-yellow-900";
        default:
          return "bg-gray-700 text-gray-100";
      }
    },
    startGame() {
      this.gameOver = false;
      this.newHighscore = false;
      this.won = false;
      this.tiles = [];
      this.score = 0;
      this.highestId = 0;
      for (var i = 0; i < this.startTiles; i++) {
        this.generateRandomNum();
      }
      if (localStorage.agBestScore) {
        this.bestScore = parseInt(localStorage.agBestScore);
      }
      document.addEventListener("keyup", this.control);
      document.addEventListener("swiped", this.control);
    },
    setTilePosition(x, y) {
      return {
        top: 0.5 + y * 6 + "rem",
        left: 0.5 + x * 6 + "rem"
      };
    }
  },
  computed: {
    gridSize() {
      return this.width * this.width;
    }
  },
  watch: {
    score(newVal) {
      if (localStorage.agBestScore < newVal) {
        this.newHighscore = true;
        localStorage.agBestScore = newVal;
        this.bestScore = newVal;
      }
    }
  },
  created() {
    document.body.classList = "overflow-hidden";
  },
  mounted() {
    if (typeof localStorage.agBestScore === "undefined") {
      localStorage.agBestScore = 0;
    }

    this.startGame();
  }
};

Vue.createApp(vueApp).mount("#app");

              
            
!
999px

Console