2048 Group C P’SSPim (Branch 1684)
✨ นางสาววนัชพร ศิลารวม
<html> <head> <style> $gridBg: #9a9a95; $color1: #F2C249; $color2: #E6772E; $color3: #4DB3B3; $color4: #3D4C53; $placeholder-tile: #F8FFE5; $font-color: #555; $border-width: 5px; @function setFontColor($color) { @if (lightness($color) > 80) { @return $bg; } @else { @return $placeholder-tile; } } * { box-sizing: border-box; } body{ animation: bgcolor 15s infinite; } html { position: relative; width: 100%; height: 100%; display: flex; flex-direction: column; font-family: "Courier New", Courier, monospace; font-family: 12px; font-weight: 900; font-size:20px; color: $font-color; background: hsl(210,100%,100%); } strong { font-weight: bold; font-family: 'Mitr', sans-serif; } p{ font-family: 'Mitr', sans-serif; } header { color: $placeholder-tile; text-align: center; } span{ display: inline-block; box-sizing: border-box; width: 4rem; height: 4rem; line-height: 4rem; margin: 0 0.4rem; font-size: 40px; border-radius:60%; background: $color1; &:nth-of-type(2) { background: $color2; } &:nth-of-type(3) { background: $color3; } &:nth-of-type(4) { background: $color4; } } .container { margin: 0 auto; padding-bottom: 3.5rem; flex: 1; width: 100%; max-width: 550px; text-align: center;} header & { padding: 0; padding: 2rem 4rem; max-width: 900px; } .scores { display: flex; position:center; justify-content: center; top:500px; } .score-container { display: flex; justify-content: center; align-items: center; margin: 1.8rem; font-size: 1.2rem; line-height: 1; color: $font-color;} &.best-score { color: $color1; } } .add { position: absolute; opacity: 0; left: 120%; top: 0; font-size: 1rem; color: hsl(0,0%,0%,0); opacity:0; } .game { position: relative; margin: 0 auto; background: $gridBg; padding: $border-width; display: inline-block; border-radius: 3px; box-sizing: border-box; } .tile { display: inline-block; box-sizing: border-box; width: 4rem; height: 4rem; line-height: 4rem; font-size: 40px; opacity: 0; z-index: 2; background: $color1; color: setFontColor($color1); display: flex; font-size: 1.8rem; transition: 110ms ease-in-out; border-radius: 60px; border: $border-width solid ; box-sizing: border-box; &--4 { background: $color2; color: setFontColor($color2); } &--8 { background: $color3; color: setFontColor($color3); } &--16 { background: $color4; color: setFontColor($color4); } &--32 { background: lighten($color2, 10%); color: setFontColor(lighten($color2, 10%)); } &--64 { background: lighten($color3, 10%); color: setFontColor(lighten($color3, 10%)); } &--128 { background: lighten($color4, 10%); color: setFontColor(lighten($color4, 10%)); } &--256 { background: lighten($color1, 10%); color: setFontColor(lighten($color1, 10%)); } &--512 { background: darken($color2, 10%); color: setFontColor(lighten($color2, 10%)); } &--1024 { background: darken($color3, 10%); color: setFontColor(lighten($color3, 10%)); } &--2048 { background: darken($color4, 10%); color: setFontColor(lighten($color4, 10%)); } &--pop { animation: pop 0.3s ease-in-out; animation-fill-mode: forwards; } &--shrink { animation: shrink 0.5s ease-in-out; animation-fill-mode: forwards; } } .tile-container { border-radius: 6px; position: relative; width: 400px; height: 400px; } .tile, .background { display: block; color: $placeholder-tile; position: absolute; width: 100px; height: 100px; box-sizing: border-box; text-align: center; } .background { z-index: 1; text-align: center; border: $border-width solid; background-color: pink; } @keyframes bgcolor { 0%,100% { background-color: hsl(0,50%,85%); } 8% { background-color: hsl(30,50%,85%); } 16% { background-color: hsl(60,65%,85%) } 24% { background-color: hsl(90,50%,85%) } 32% { background-color: hsl(120,50%,85%) } 40% { background-color: hsl(150,50%,85%) } 48% { background-color: hsl(180,50%,85%) } 56% { background-color: hsl(210,50%,85%) } 64% { background-color: hsl(240,50%,85%) } 72% { background-color: hsl(270,50%,85%) } 80% { background-color: hsl(300,50%,85%) } 88% { background-color: hsl(330,50%,85%) } } @keyframes pop { 0% { transform: scale(0.5); opacity: 0; } 90% { transform: scale(1.1); opacity: 1; } 100% { transform: scale(1); opacity: 1; } } @keyframes shrink { 0% { transform: scale(1); opacity: 1; } 100% { transform: scale(0.9); opacity: 0.9; } } .btn { font-family: inherit; font-size: 1rem; border: none; background: $color3; letter-spacing: 1px; color: white; font-weight: 300; padding: 0.9em 1.5em; border-radius: 3px; border: 1px solid transparent; cursor: pointer; &:hover { background-color: darken($color3, 10%); } &:active { background-color: darken($color3, 20%); } &:focus { box-shadow: 0 0 10px darken($color3, 20%) inset; outline: none; } } .end { opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; display: flex; flex-direction: column; justify-content: center; align-items: center; background: rgba($font-color, 0.9); color: white; font-size: 2rem; transition: opacity 0.3s ease-in-out;} btn { margin-top: 1rem; } &.active { opacity: 1; z-index: 1000; } } </style> </head> <header> <div class="container"> <h1><span>2</span><span>0</span><span>4</span><span>8</span> </h1> </div> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Mitr&display=swap" rel="stylesheet"> </header> <div class="container"> <div class="directions"> <p><strong>เล่นยังไง:</strong> ใช้ ⬅ ⬆ ⬇ ➡ หรือ W A S D เพื่อขยับกล่องตัวเลข, เมื่อกล่องสองอันชนกันจะทำให้กล่องบวกกัน</p> <p><strong>เป้าหมาย:</strong> รวมกล่องเข้าด้วยกันจนมีค่า 2048 ในกล่องเดียว</p> </div> <div class="scores"> <div class="score-container best-score"> best: <div class="score"> <div id="bestScore">0</div> </div> </div> <div class="score-container"> score: <div class="score"> <div id="score">0</div> <div class="add" id="add"></div> </div> </div> </div> <div class="game"> <div id="tile-container" class="tile-container"></div> <div class="end" id="end">Game Over<div class="monkey">🤖</div><button class="btn not-recommended__item js-restart-btn" id="try-again">Try Again</button></div> <p class="inspired">for educational purpose only!.</p> <p class="inspired">for<a href="https://codepen.io/ramenhog/pen/JWZzry" target="_blank">Original</a>.</p> </div> </div> <script> let game = null; let bestScore = 0; const scoreDiv = document.getElementById('score'); const bestScoreDiv = document.getElementById('bestScore'); const addDiv = document.getElementById('add'); const endDiv = document.getElementById('end'); const size = 4; let nextId = 1; let score = 0; function initGame() { game = Array(size*size).fill(null); // 4 x 4 grid, represented as an array initBestScore(); } function initBestScore() { bestScore = localStorage.getItem('bestScore') || 0; bestScoreDiv.innerHTML = bestScore; } function updateDOM(before, after) { const newElements = getNewElementsDOM(before, after); const existingElements = getExistingElementsDOM(before, after); const mergedTiles = getMergedTiles(after); removeElements(mergedTiles); drawGame(newElements, true); drawGame(existingElements); } function removeElements(mergedTiles) { for (let tile of mergedTiles) { for (let id of tile.mergedIds) { const currentElm = document.getElementById(id); positionTile(tile, currentElm); currentElm.classList.add('tile--shrink'); setTimeout(() => { currentElm.remove(); }, 100); } } } function getMergedTiles(after) { return after.filter((tile) => tile && tile.mergedIds); } function getNewElementsDOM(before, after) { const beforeIds = before.filter((tile) => tile).map((tile) => tile.id); const newElements = after.filter((tile) => { return tile && beforeIds.indexOf(tile.id) === -1; }); return newElements; } function getExistingElementsDOM(before, after) { const beforeIds = before.filter((tile) => tile).map((tile) => tile.id); const existingElements = after.filter((tile) => { return tile && beforeIds.indexOf(tile.id) !== -1; }); return existingElements; } function drawBackground() { const tileContainer = document.getElementById('tile-container'); tileContainer.innerHTML = ''; for (let i = 0; i < game.length; i++) { const tile = game[i]; const tileDiv = document.createElement('div'); const x = i % size; const y = Math.floor(i / size); tileDiv.style.top = `${y*100}px`; tileDiv.style.left = `${x*100}px`; tileDiv.classList.add("background"); tileContainer.appendChild(tileDiv); } } function positionTile(tile, elm) { const x = tile.index % size; const y = Math.floor(tile.index / size); elm.style.top = `${y*100}px`; elm.style.left = `${x*100}px`; } function drawGame(tiles, isNew) { const tileContainer = document.getElementById('tile-container'); for (let i = 0; i < tiles.length; i++) { const tile = tiles[i]; if (tile) { if (isNew) { const tileDiv = document.createElement('div'); positionTile(tile, tileDiv); tileDiv.classList.add('tile', `tile--${tile.value}`); tileDiv.id = tile.id; setTimeout(() => { tileDiv.classList.add("tile--pop"); }, tile.mergedIds ? 1 : 150); tileDiv.innerHTML = `<p>${tile.value}</p>`; tileContainer.appendChild(tileDiv); } else { const currentElement = document.getElementById(tile.id); positionTile(tile, currentElement); } } } } function gameOver() { if (game.filter((number)=>number===null).length === 0) { const sameNeighbors = game.find((tile, i)=>{ const isRightSame = game[i+1] && (i+1)%4 !== 0 ? tile.value === game[i+1].value : false; const isDownSame = game[i+4] ? tile.value === game[i+4].value : false; if (isRightSame || isDownSame) { return true; } return false; }); return !sameNeighbors; } } function generateNewNumber() { // 0.9 probability of 2, 0.1 probability of 4 const p = Math.random() * 100; return (p <= 90) ? 2 : 4; } function addRandomNumber() { // Adds either a 2 or a 4 to an empty position in the game array const emptyCells = game.map((_, index) => index) .filter((index) => game[index] === null); if (emptyCells.length === 0) { return; } const newPos = emptyCells[Math.floor(Math.random() * emptyCells.length)]; const newObj = { id: nextId++, index: newPos, value: generateNewNumber() }; game.splice(newPos, 1, newObj); } function getIndexForPoint(x, y) { return y*size + x; } function reflectGrid(grid) { let reflectedGame = Array(size*size).fill(0); for (let row = 0; row < size; row++) { for (let col = 0; col < size; col++) { const index1 = getIndexForPoint(col, row); const index2 = getIndexForPoint(size-col-1, row); reflectedGame[index1] = grid[index2]; } } return reflectedGame; } function rotateLeft90Deg(grid) { let rotatedGame = Array(size*size).fill(0); for (let row = 0; row < size; row++) { for (let col = 0; col < size; col++) { const index1 = getIndexForPoint(col, row); const index2 = getIndexForPoint(size-1-row, col); rotatedGame[index1] = grid[index2]; } } return rotatedGame; } function rotateRight90Deg(grid) { let rotatedGame = Array(size*size).fill(0); for (let row = 0; row < size; row++) { for (let col = 0; col < size; col++) { const index1 = getIndexForPoint(col, row); const index2 = getIndexForPoint(row,size-1-col); rotatedGame[index1] = grid[index2]; } } return rotatedGame; } /* For any cell whose neighbor to the right is empty, move that cell to the right. For any cell whose neighbor to the right is equal to the same value, combine the values together (e.g. 2+2 = 4) */ function shiftGameRight(gameGrid) { // reflect game grid let reflectedGame = reflectGrid(gameGrid); // shift left reflectedGame = shiftGameLeft(reflectedGame); // reflect back return reflectGrid(reflectedGame); } function shiftGameLeft(gameGrid) { let newGameState = []; let totalAdd = 0; // for rows for (let i = 0; i < size; i++) { // for columns const firstPos = 4*i; const lastPos = (size)+4*i; const currentRow = gameGrid.slice(firstPos,lastPos); const filteredRow = currentRow.filter((row)=>row); for (let row of filteredRow) { delete row.mergedIds; } for (let j = 0; j < filteredRow.length - 1; j++) { if (filteredRow[j].value === filteredRow[j+1].value) { const sum = filteredRow[j].value * 2; filteredRow[j] = { id: nextId++, mergedIds: [filteredRow[j].id, filteredRow[j+1].id], value: sum }; filteredRow.splice(j+1,1); score += sum; totalAdd += sum; } } while(filteredRow.length < size) { filteredRow.push(null); }; newGameState = [...newGameState, ...filteredRow]; } if (totalAdd > 0) { scoreDiv.innerHTML = score; addDiv.innerHTML = `+${totalAdd}`; addDiv.classList.add('active'); setTimeout(function() { addDiv.classList.remove("active"); }, 800); if (score > bestScore) { localStorage.setItem('bestScore', score); initBestScore(); } } return newGameState; } function shiftGameUp(gameGrid) { let rotatedGame = rotateLeft90Deg(gameGrid); rotatedGame = shiftGameLeft(rotatedGame); return rotateRight90Deg(rotatedGame); } function shiftGameDown(gameGrid) { let rotatedGame = rotateRight90Deg(gameGrid); rotatedGame = shiftGameLeft(rotatedGame); return rotateLeft90Deg(rotatedGame); } const buttons = document.querySelectorAll(".js-restart-btn"); const length = buttons.length; for (let i = 0; i < length; i++) { if (document.addEventListener) { buttons[i].addEventListener("click", function() { newGameStart(); }); } else { buttons[i].attachEvent("onclick", function() { newGameStart(); }); }; }; document.addEventListener("keydown", handleKeypress); document.addEventListener('touchstart', handleTouchStart, false); document.addEventListener('touchmove', handleTouchMove, false); let xDown = null; let yDown = null; function handleTouchStart(evt) { xDown = evt.touches[0].clientX; yDown = evt.touches[0].clientY; }; function handleTouchMove(evt) { const prevGame = [...game]; if ( !xDown || !yDown ) { return; } const xUp = evt.touches[0].clientX; const yUp = evt.touches[0].clientY; const xDiff = xDown - xUp; const yDiff = yDown - yUp; if ( Math.abs(xDiff) > Math.abs(yDiff) ) { if ( xDiff > 0 ) { game = shiftGameLeft(game); } else { game = shiftGameRight(game); } } else { if ( yDiff > 0 ) { game = shiftGameUp(game); } else { game = shiftGameDown(game); } } game = game.map((tile, index) => { if (tile) { return { ...tile, index }; } else { return null; } }); if (_.isEqual(prevGame, game)) return; addRandomNumber(); updateDOM(prevGame, game); if (gameOver()) { setTimeout(() => { endDiv.classList.add('active'); }, 800); return; } xDown = null; yDown = null; }; function handleKeypress(evt) { var modifiers = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey; var whichKey= event.which; const prevGame = [...game]; if (!modifiers) { event.preventDefault(); switch (whichKey) { case 37: game = shiftGameLeft(game); break; case 65: game = shiftGameLeft(game); break; case 38: game = shiftGameUp(game); break; case 87: game = shiftGameUp(game); break; case 39: game = shiftGameRight(game); break; case 68: game = shiftGameRight(game); break; case 40: game = shiftGameDown(game); break; case 83: game = shiftGameDown(game); break; } game = game.map((tile, index) => { if (tile) { return { ...tile, index }; } else { return null; } }); if (_.isEqual(prevGame, game)) return; addRandomNumber(); updateDOM(prevGame, game); if (gameOver()) { setTimeout(() => { endDiv.classList.add('active'); }, 800); return; } } } function newGameStart() { document.getElementById('tile-container').innerHTML = ''; endDiv.classList.remove('active'); score = 0; scoreDiv.innerHTML = score; initGame(); drawBackground(); const previousGame = [...game]; addRandomNumber(); addRandomNumber(); updateDOM(previousGame, game); } newGameStart(); </script> </html>