| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471 |
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
- <title>2048</title>
- <style>
- * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
- html, body {
- height: 100%;
- font-family: 'Clear Sans', 'Helvetica Neue', Arial, sans-serif;
- background: #faf8ef;
- color: #776e65;
- display: flex;
- justify-content: center;
- align-items: center;
- overflow: hidden;
- }
- .container {
- width: min(92vw, 480px);
- position: relative;
- }
- /* 顶部栏:标题 + 分数 */
- .header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 14px;
- flex-wrap: wrap;
- gap: 10px;
- }
- .title {
- font-size: clamp(40px, 11vw, 64px);
- font-weight: 800;
- color: #776e65;
- line-height: 1;
- }
- .scores { display: flex; gap: 8px; }
- .score-box {
- background: #bbada0;
- border-radius: 6px;
- padding: 8px 16px;
- text-align: center;
- min-width: 78px;
- }
- .score-label {
- color: #eee4da;
- font-size: 11px;
- font-weight: 700;
- text-transform: uppercase;
- letter-spacing: 1px;
- }
- .score-value { color: #fff; font-size: 22px; font-weight: 800; }
- .score-delta {
- position: absolute;
- color: rgba(119,110,101,.9);
- font-size: 20px;
- font-weight: 800;
- animation: deltaUp .6s ease forwards;
- pointer-events: none;
- }
- @keyframes deltaUp { 0%{opacity:.9;transform:translateY(0)} 100%{opacity:0;transform:translateY(-32px)} }
- /* 说明 + 新游戏按钮 */
- .bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; gap: 12px; }
- .intro { font-size: 13px; line-height: 1.5; flex: 1; }
- .btn {
- background: #8f7a66;
- color: #f9f6f2;
- border: none;
- border-radius: 6px;
- padding: 10px 18px;
- font-size: 14px;
- font-weight: 700;
- cursor: pointer;
- transition: background .15s;
- white-space: nowrap;
- }
- .btn:hover { background: #7c6655; }
- /* 棋盘 */
- .board-wrap { position: relative; width: 100%; }
- .grid {
- background: #bbada0;
- border-radius: 8px;
- padding: 10px;
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- grid-template-rows: repeat(4, 1fr);
- gap: 10px;
- aspect-ratio: 1 / 1;
- position: relative;
- touch-action: none;
- }
- .cell-bg {
- background: rgba(238, 228, 218, 0.35);
- border-radius: 6px;
- }
- /* 方块层(绝对定位覆盖在网格上) */
- .tile-layer {
- position: absolute;
- inset: 10px;
- pointer-events: none;
- }
- .tile {
- position: absolute;
- width: calc((100% - 30px) / 4);
- height: calc((100% - 30px) / 4);
- border-radius: 6px;
- display: flex;
- align-items: center;
- justify-content: center;
- font-weight: 800;
- transition: transform .12s ease;
- line-height: 1;
- }
- .tile-new { animation: pop .18s ease; }
- .tile-merged { animation: merge .18s ease; z-index: 2; }
- @keyframes pop { 0%{transform:var(--pos) scale(0)} 60%{transform:var(--pos) scale(1.1)} 100%{transform:var(--pos) scale(1)} }
- @keyframes merge { 0%{transform:var(--pos) scale(1)} 50%{transform:var(--pos) scale(1.18)} 100%{transform:var(--pos) scale(1)} }
- /* 方块配色 */
- .t2{background:#eee4da;color:#776e65;font-size:clamp(24px,7vw,40px)}
- .t4{background:#ede0c8;color:#776e65;font-size:clamp(24px,7vw,40px)}
- .t8{background:#f2b179;color:#f9f6f2;font-size:clamp(24px,7vw,40px)}
- .t16{background:#f59563;color:#f9f6f2;font-size:clamp(22px,6.5vw,38px)}
- .t32{background:#f67c5f;color:#f9f6f2;font-size:clamp(22px,6.5vw,38px)}
- .t64{background:#f65e3b;color:#f9f6f2;font-size:clamp(22px,6.5vw,38px)}
- .t128{background:#edcf72;color:#f9f6f2;font-size:clamp(20px,5.5vw,34px);box-shadow:0 0 12px rgba(243,215,116,.6)}
- .t256{background:#edcc61;color:#f9f6f2;font-size:clamp(20px,5.5vw,34px);box-shadow:0 0 14px rgba(243,215,116,.7)}
- .t512{background:#edc850;color:#f9f6f2;font-size:clamp(20px,5.5vw,34px);box-shadow:0 0 16px rgba(243,215,116,.8)}
- .t1024{background:#edc53f;color:#f9f6f2;font-size:clamp(18px,4.5vw,30px);box-shadow:0 0 18px rgba(243,215,116,.9)}
- .t2048{background:#edc22e;color:#f9f6f2;font-size:clamp(18px,4.5vw,30px);box-shadow:0 0 22px rgba(243,215,116,1)}
- .t-super{background:#3c3a32;color:#f9f6f2;font-size:clamp(16px,4vw,28px)}
- /* 遮罩(胜利/失败) */
- .overlay {
- position: absolute;
- inset: 0;
- background: rgba(238,228,218,.75);
- border-radius: 8px;
- display: none;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- z-index: 10;
- backdrop-filter: blur(2px);
- }
- .overlay.show { display: flex; animation: fadeIn .4s ease; }
- @keyframes fadeIn { from{opacity:0} to{opacity:1} }
- .overlay h2 { font-size: 40px; font-weight: 800; margin-bottom: 20px; }
- .overlay.win h2 { color: #edc22e; }
- .overlay.lose h2 { color: #776e65; }
- .overlay .btn { font-size: 16px; padding: 12px 24px; }
- .footer { text-align: center; margin-top: 14px; font-size: 12px; color: #bbada0; }
- </style>
- </head>
- <body>
- <div class="container">
- <div class="header">
- <div class="title">2048</div>
- <div class="scores">
- <div class="score-box"><div class="score-label">分数</div><div class="score-value" id="score">0</div></div>
- <div class="score-box"><div class="score-label">最高</div><div class="score-value" id="best">0</div></div>
- </div>
- </div>
- <div class="bar">
- <div class="intro"><b>玩法:</b>合并相同数字方块,拼出 2048!<br>键盘方向键/WASD 或手指滑动操作。</div>
- <button class="btn" id="newGame">新游戏</button>
- </div>
- <div class="board-wrap">
- <div class="grid" id="grid">
- <!-- 16 个背景格 -->
- <div class="cell-bg"></div><div class="cell-bg"></div><div class="cell-bg"></div><div class="cell-bg"></div>
- <div class="cell-bg"></div><div class="cell-bg"></div><div class="cell-bg"></div><div class="cell-bg"></div>
- <div class="cell-bg"></div><div class="cell-bg"></div><div class="cell-bg"></div><div class="cell-bg"></div>
- <div class="cell-bg"></div><div class="cell-bg"></div><div class="cell-bg"></div><div class="cell-bg"></div>
- </div>
- <div class="tile-layer" id="tileLayer"></div>
- <div class="overlay" id="overlay">
- <h2 id="overlayText"></h2>
- <button class="btn" id="overlayBtn">再来一局</button>
- </div>
- </div>
- <div class="footer">用方向键 / WASD / 滑动来游玩</div>
- </div>
- <script>
- (function () {
- 'use strict';
- const SIZE = 4;
- const WIN_VAL = 2048;
- let grid, score, best, hasWon, movedThisTurn, animating;
- const $ = (id) => document.getElementById(id);
- const tileLayer = $('tileLayer');
- const overlay = $('overlay');
- const overlayText = $('overlayText');
- const scoreEl = $('score');
- const bestEl = $('best');
- /* ---------- 核心数据 ---------- */
- function emptyGrid() { return Array.from({ length: SIZE }, () => Array(SIZE).fill(0)); }
- function clone(g) { return g.map(r => r.slice()); }
- // 在空格随机放一个 2(90%) 或 4(10%)
- function addRandom(g) {
- const empty = [];
- for (let r = 0; r < SIZE; r++)
- for (let c = 0; c < SIZE; c++)
- if (g[r][c] === 0) empty.push([r, c]);
- if (empty.length === 0) return false;
- const [r, c] = empty[Math.floor(Math.random() * empty.length)];
- g[r][c] = Math.random() < 0.9 ? 2 : 4;
- return true;
- }
- /* ---------- 移动 / 合并 ---------- */
- // 向左移动一行,返回 {row, gained, moved}
- function slideLeftRow(row) {
- const filtered = row.filter(v => v !== 0);
- const merged = [];
- let gained = 0;
- for (let i = 0; i < filtered.length; i++) {
- if (i + 1 < filtered.length && filtered[i] === filtered[i + 1]) {
- const val = filtered[i] * 2;
- merged.push(val);
- gained += val;
- i++; // 跳过下一个
- } else {
- merged.push(filtered[i]);
- }
- }
- while (merged.length < SIZE) merged.push(0);
- const moved = row.some((v, i) => v !== merged[i]);
- return { row: merged, gained, moved };
- }
- function transpose(g) {
- return g[0].map((_, c) => g.map(r => r[c]));
- }
- function reverseRows(g) { return g.map(r => r.slice().reverse()); }
- // direction: 'left' | 'right' | 'up' | 'down'
- function move(g, direction) {
- let work = clone(g);
- if (direction === 'up') work = transpose(work);
- if (direction === 'down') work = reverseRows(transpose(work));
- if (direction === 'right') work = reverseRows(work);
- let gained = 0, moved = false;
- const result = work.map(row => {
- const res = slideLeftRow(row);
- gained += res.gained;
- if (res.moved) moved = true;
- return res.row;
- });
- let final = result;
- if (direction === 'up') final = transpose(result);
- if (direction === 'down') final = transpose(reverseRows(result));
- if (direction === 'right') final = reverseRows(result);
- return { grid: final, gained, moved };
- }
- /* ---------- 状态判断 ---------- */
- function canMove(g) {
- for (let r = 0; r < SIZE; r++)
- for (let c = 0; c < SIZE; c++) {
- if (g[r][c] === 0) return true;
- if (c + 1 < SIZE && g[r][c] === g[r][c + 1]) return true;
- if (r + 1 < SIZE && g[r][c] === g[r + 1][c]) return true;
- }
- return false;
- }
- function hasValue(g, v) {
- return g.some(row => row.some(cell => cell >= v));
- }
- /* ---------- 渲染 ---------- */
- function tileClass(v) {
- if (v <= 2048) return 't' + v;
- return 't-super';
- }
- // 计算方块在 tile-layer 内的坐标位置(百分比)
- function pos(r, c) {
- const pct = (idx) => `calc(${idx} * (100% + 10px) / 4)`; // gap=10px
- return { left: pct(c), top: pct(r) };
- }
- function render(opts) {
- opts = opts || {};
- const newCells = opts.newCells || [];
- const mergedCells = opts.mergedCells || [];
- tileLayer.innerHTML = '';
- for (let r = 0; r < SIZE; r++) {
- for (let c = 0; c < SIZE; c++) {
- const v = grid[r][c];
- if (v === 0) continue;
- const t = document.createElement('div');
- const isNew = newCells.some(p => p[0] === r && p[1] === c);
- const isMerged = mergedCells.some(p => p[0] === r && p[1] === c);
- t.className = 'tile ' + tileClass(v);
- if (isNew) t.classList.add('tile-new');
- if (isMerged) t.classList.add('tile-merged');
- const p = pos(r, c);
- // 用 CSS 变量统一控制位置,配合 scale 动画
- const tr = `translate(${p.left}, ${p.top})`;
- t.style.setProperty('--pos', tr);
- t.style.left = '0';
- t.style.top = '0';
- t.style.transform = tr;
- t.textContent = v;
- tileLayer.appendChild(t);
- }
- }
- }
- function showDelta(d) {
- if (d <= 0) return;
- const el = document.createElement('div');
- el.className = 'score-delta';
- el.textContent = '+' + d;
- const box = $('score').parentElement;
- el.style.left = '50%';
- el.style.top = '0';
- el.style.transform = 'translateX(-50%)';
- box.style.position = 'relative';
- box.appendChild(el);
- setTimeout(() => el.remove(), 600);
- }
- function updateScore() {
- scoreEl.textContent = score;
- if (score > best) {
- best = score;
- bestEl.textContent = best;
- localStorage.setItem('best2048', best);
- }
- }
- function showOverlay(type) {
- overlay.className = 'overlay show ' + type;
- overlayText.textContent = type === 'win' ? '🎉 你赢了!' : '游戏结束';
- $('overlayBtn').textContent = type === 'win' ? '继续挑战' : '再来一局';
- }
- function hideOverlay() { overlay.className = 'overlay'; }
- /* ---------- 跟踪合并位置(用于动画高亮) ---------- */
- function trackMerges(prevGrid, newGrid) {
- // 近似:值翻倍且非新生成的格子视为合并目标
- const merged = [];
- for (let r = 0; r < SIZE; r++)
- for (let c = 0; c < SIZE; c++) {
- const pv = prevGrid[r][c];
- const nv = newGrid[r][c];
- if (nv !== 0 && pv !== nv && nv % 2 === 0 && (pv === 0 || nv === pv * 2)) {
- // 粗略合并点标记,用于动画
- merged.push([r, c]);
- }
- }
- return merged;
- }
- /* ---------- 一次操作流程 ---------- */
- function handleMove(direction) {
- if (animating || overlay.classList.contains('show')) return;
- const prev = clone(grid);
- const res = move(grid, direction);
- if (!res.moved) return;
- animating = true;
- grid = res.grid;
- if (res.gained > 0) {
- score += res.gained;
- showDelta(res.gained);
- }
- updateScore();
- const mergedCells = trackMerges(prev, grid);
- render({ mergedCells });
- setTimeout(() => {
- // 记录加方块前
- const before = clone(grid);
- addRandom(grid);
- // 新方块 = before 为0但 grid 非0 且值<=4
- const newCells = [];
- for (let r = 0; r < SIZE; r++)
- for (let c = 0; c < SIZE; c++)
- if (before[r][c] === 0 && grid[r][c] !== 0) newCells.push([r, c]);
- render({ newCells, mergedCells });
- animating = false;
- if (!hasWon && hasValue(grid, WIN_VAL)) {
- hasWon = true;
- showOverlay('win');
- } else if (!canMove(grid)) {
- showOverlay('lose');
- }
- }, 120);
- }
- /* ---------- 新游戏 ---------- */
- function newGame() {
- grid = emptyGrid();
- score = 0;
- hasWon = false;
- animating = false;
- hideOverlay();
- addRandom(grid);
- addRandom(grid);
- updateScore();
- // 标记初始两个方块为新方块动画
- const newCells = [];
- for (let r = 0; r < SIZE; r++)
- for (let c = 0; c < SIZE; c++)
- if (grid[r][c] !== 0) newCells.push([r, c]);
- render({ newCells });
- }
- /* ---------- 输入 ---------- */
- const keyMap = {
- ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down',
- a: 'left', d: 'right', w: 'up', s: 'down',
- A: 'left', D: 'right', W: 'up', S: 'down',
- };
- document.addEventListener('keydown', (e) => {
- const dir = keyMap[e.key];
- if (dir) { e.preventDefault(); handleMove(dir); }
- });
- // 触摸滑动
- const gridEl = $('grid');
- let tsx = 0, tsy = 0;
- gridEl.addEventListener('touchstart', (e) => {
- const t = e.touches[0];
- tsx = t.clientX; tsy = t.clientY;
- }, { passive: true });
- gridEl.addEventListener('touchend', (e) => {
- const t = e.changedTouches[0];
- const dx = t.clientX - tsx, dy = t.clientY - tsy;
- const ax = Math.abs(dx), ay = Math.abs(dy);
- if (Math.max(ax, ay) < 24) return;
- if (ax > ay) handleMove(dx > 0 ? 'right' : 'left');
- else handleMove(dy > 0 ? 'down' : 'up');
- }, { passive: true });
- // 按钮
- $('newGame').addEventListener('click', newGame);
- $('overlayBtn').addEventListener('click', () => {
- if (overlay.classList.contains('win')) {
- // 继续:仅关闭遮罩
- hideOverlay();
- } else {
- newGame();
- }
- });
- /* ---------- 启动 ---------- */
- best = parseInt(localStorage.getItem('best2048') || '0', 10);
- bestEl.textContent = best;
- newGame();
- })();
- </script>
- </body>
- </html>
|