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 class="game-container">
  <div class="game-board" id="game-board"></div>
  <div class="game-info">
    <h1>Game 2048</h1>
    <h3>Points: <span id="points">0</span></h3>
    <button id="reset-button">Reset Game</button>
    <div id="message-container"></div>
  </div>
</div>
<script src="script.js"></script>
              
            
!

CSS

              
                body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background-color: #f0f0f0;
}
h1 {
  color:#88b;
}
h3 {
  border-bottom:solid 1px #88b;
  padding:5px 20px;
  color:#888;
}
.game-container {
  border-radius:10px;
  display: flex;
  align-items: flex-start;
  border: 4px solid #ccc;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  overflow: hidden;
}

.game-board {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  padding: 10px;
}

.tile {
  border-radius:10px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  background-color: #ccc;
  width: 70px;
  height: 70px;
}

/* 各数字に対応するタイル */
.tile-2 { background-color: #eee4da; }
.tile-4 { background-color: #ede0c8; }
.tile-8 { background-color: #f2b179; }
.tile-16 { background-color: #f59563; }
.tile-32 { background-color: #f67c5f; }
.tile-64 { background-color: #f65e3b; }
.tile-128 { background-color: #edcf72; }
.tile-256 { background-color: #edcc61; }
.tile-512 { background-color: #edc850; }
.tile-1024 { background-color: #edc53f; }
.tile-2048 { background-color: #edc22e; }

.game-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

/* ボタン */
button {
  background-color: #88b;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 5px;
  font-size: 18px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: color 0.3s ease;
}
button::before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.2);
  transform: skewX(-45deg);
  transition: left 0.3s ease;
}
button:hover::before {
  left: 100%;
}
#game-over,#game-won {
  margin-top:20px;
  color:#c88;
  font-size:1.5rem;
  font-weight:bold;
}
              
            
!

JS

              
                const board = document.getElementById('game-board');
const pointsDisplay = document.getElementById('points');
const resetButton = document.getElementById('reset-button');
const messageContainer = document.getElementById('message-container');
const gridSize = 4;
let tiles = [];
let points = 0;
let isGameOverShown = false;
let gameOverMessage = null;
let gameWonMessage = null;

function createTile(value) {
  const tile = document.createElement('div');
  tile.className = 'tile';
  tile.textContent = value !== 0 ? value : '';
  return tile;
}

function initializeBoard() {
  for (let i = 0; i < gridSize; i++) {
    for (let j = 0; j < gridSize; j++) {
      const tile = createTile(0);
      board.appendChild(tile);
      tiles.push({ element: tile, value: 0 });
    }
  }
}

function getRandomPosition() {
  return Math.floor(Math.random() * gridSize * gridSize);
}

function addRandomTile() {
  const emptyTiles = tiles.filter(tile => tile.value === 0);
  if (emptyTiles.length === 0) return;

  const randomTile = emptyTiles[getRandomPosition() % emptyTiles.length];
  randomTile.value = Math.random() < 0.9 ? 2 : 4;
  updateBoard();
}

function updateBoard() {
  tiles.forEach(tile => {
    tile.element.textContent = tile.value !== 0 ? tile.value : '';
    tile.element.className = 'tile';
    if (tile.value !== 0) {
      tile.element.classList.add(`tile-${tile.value}`);
    }
  });
  pointsDisplay.textContent = points;
}

function getNeighbors(index) {
  const neighbors = [];
  const row = Math.floor(index / gridSize);
  const col = index % gridSize;

  if (row > 0) neighbors.push((row - 1) * gridSize + col); // 上
  if (row < gridSize - 1) neighbors.push((row + 1) * gridSize + col); // 下
  if (col > 0) neighbors.push(row * gridSize + col - 1); // 左
  if (col < gridSize - 1) neighbors.push(row * gridSize + col + 1); // 右

  return neighbors;
}

function isGameOver() {
  if (tiles.every(tile => tile.value !== 0)) {
    for (let i = 0; i < tiles.length; i++) {
      const tile = tiles[i];
      const neighbors = getNeighbors(i);
      for (const neighbor of neighbors) {
        if (tiles[neighbor].value === tile.value) {
          return false;
        }
      }
    }
    return true;
  }
  return false;
}

function isGameWon() {
  return tiles.some(tile => tile.value === 2048);
}

function showGameOverMessage() {
  if (!isGameOverShown) {
    gameOverMessage = document.createElement('div');
    gameOverMessage.id = 'game-over';
    gameOverMessage.textContent = 'Game Over';
    messageContainer.appendChild(gameOverMessage);
    isGameOverShown = true;
  }
}

function removeGameOverMessage() {
  if (gameOverMessage) {
    gameOverMessage.remove();
    gameOverMessage = null;
    isGameOverShown = false;
  }
}

function showGameWonMessage() {
  if (!gameWonMessage) {
    gameWonMessage = document.createElement('div');
    gameWonMessage.id = 'game-won';
    gameWonMessage.textContent = 'Congratulations! You Win!';
    messageContainer.appendChild(gameWonMessage);
  }
}

function removeGameWonMessage() {
  if (gameWonMessage) {
    gameWonMessage.remove();
    gameWonMessage = null;
  }
}

// キー操作によるゲームプレイの実装
document.addEventListener('keydown', handleKeydown);

function handleKeydown(event) {
  const arrowKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
  if (arrowKeys.includes(event.key)) {
    event.preventDefault();
    if (isGameOver() && !isGameOverShown) {
      showGameOverMessage();
      return;
    }
    if (isGameOverShown) {
      removeGameOverMessage();
    }
    if (gameWonMessage) {
      removeGameWonMessage();
    }
    const moveDirection = event.key.replace('Arrow', '');
    moveTiles(moveDirection);
    addRandomTile();
    if (isGameWon()) {
      showGameWonMessage();
    }
    if (isGameOver()) {
      showGameOverMessage();
    }
  }
}

// タイルの移動処理
function moveTiles(direction) {
  const rowVectors = {
    Up: [-1, 0],
    Down: [1, 0],
    Left: [0, -1],
    Right: [0, 1]
  };

  const [r, c] = rowVectors[direction];
  let moved = false;

  for (let i = 0; i < gridSize; i++) {
    for (let j = 0; j < gridSize; j++) {
      const currentTile = tiles[i * gridSize + j];
      if (currentTile.value !== 0) {
        let newRow = i + r;
        let newCol = j + c;

        while (newRow >= 0 && newRow < gridSize && newCol >= 0 && newCol < gridSize) {
          const newTile = tiles[newRow * gridSize + newCol];

          if (newTile.value === 0) {
            newTile.value = currentTile.value;
            currentTile.value = 0;
            moved = true;
          } else if (newTile.value === currentTile.value) {
            newTile.value *= 2;
            points += newTile.value;
            currentTile.value = 0;
            moved = true;
            break;
          } else {
            break;
          }

          newRow += r;
          newCol += c;
        }
      }
    }
  }

  if (moved) {
    updateBoard();
  }
}

// ゲームの初期化
initializeBoard();
addRandomTile();
addRandomTile();

// リセットボタンのクリックイベント
resetButton.addEventListener('click', resetGame);

function resetGame() {
  if (gameOverMessage) {
    removeGameOverMessage();
  }
  if (gameWonMessage) {
    removeGameWonMessage();
  }
  tiles = [];
  points = 0;
  pointsDisplay.textContent = points;
  board.innerHTML = '';
  initializeBoard();
  addRandomTile();
  addRandomTile();
}

              
            
!
999px

Console