HTML2048小游戏(最新版)

比上一篇文章的2048更好一点。 控制方法:WASD键(小写)或页面上四个按钮

效果图如下: 源代码在图片后面

源代码

·HTML·

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2048 Game</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="game-container">
        <div id="game-board"></div>
        <div id="controls">
            <button id="up">W</button>
            <button id="left">A</button>
            <button id="down">S</button>
            <button id="right">D</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

·CSS·

css 复制代码
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-family: 'Arial', sans-serif;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #faf8ef;
}

#game-container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

#game-board {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(4, 1fr);
    gap: 10px;
    background-color: #bbada0;
    padding: 10px;
    border-radius: 10px;
    margin-bottom: 20px;
}

.tile {
    width: 80px;
    height: 80px;
    background-color: #cdc1b4;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24px;
    border-radius: 10px;
    transition: all 0.2s ease-in-out;
}

#controls {
    display: flex;
    gap: 10px;
}

button {
    width: 60px;
    height: 60px;
    font-size: 20px;
    border-radius: 10px;
    background-color: #8f7a66;
    color: white;
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: #9f8b76;
}

·JavaScript·

javascript 复制代码
document.addEventListener('DOMContentLoaded', () => {
    const boardSize = 4;
    let board = [];
    let score = 0;

    const gameBoard = document.getElementById('game-board');
    const buttons = {
        up: document.getElementById('up'),
        down: document.getElementById('down'),
        left: document.getElementById('left'),
        right: document.getElementById('right')
    };

    function initBoard() {
        for (let i = 0; i < boardSize * boardSize; i++) {
            const tile = document.createElement('div');
            tile.classList.add('tile');
            gameBoard.appendChild(tile);
        }
        board = Array.from(document.querySelectorAll('.tile'));
        generateTile();
        generateTile();
        updateBoard();
    }

    function generateTile() {
        let emptyTiles = board.filter(tile => !tile.textContent);
        if (emptyTiles.length > 0) {
            let randomTile = emptyTiles[Math.floor(Math.random() * emptyTiles.length)];
            randomTile.textContent = Math.random() < 0.9 ? '2' : '4';
        }
    }

    function updateBoard() {
        board.forEach(tile => {
            const value = tile.textContent;
            tile.style.backgroundColor = getTileColor(value);
        });
    }

    function getTileColor(value) {
        switch (value) {
            case '2': return '#eee4da';
            case '4': return '#ede0c8';
            case '8': return '#f2b179';
            case '16': return '#f59563';
            case '32': return '#f67c5f';
            case '64': return '#f65e3b';
            case '128': return '#edcf72';
            case '256': return '#edcc61';
            case '512': return '#edc850';
            case '1024': return '#edc53f';
            case '2048': return '#edc22e';
            default: return '#cdc1b4';
        }
    }

    function move(direction) {
        switch (direction) {
            case 'up': moveUp(); break;
            case 'down': moveDown(); break;
            case 'left': moveLeft(); break;
            case 'right': moveRight(); break;
        }
        generateTile();
        updateBoard();
    }

    function moveUp() {
        for (let i = 0; i < boardSize; i++) {
            let column = [];
            for (let j = 0; j < boardSize; j++) {
                column.push(board[i + j * boardSize].textContent);
            }
            let newColumn = slideTiles(column);
            for (let j = 0; j < boardSize; j++) {
                board[i + j * boardSize].textContent = newColumn[j];
            }
        }
    }

    function moveDown() {
        for (let i = 0; i < boardSize; i++) {
            let column = [];
            for (let j = 0; j < boardSize; j++) {
                column.push(board[i + j * boardSize].textContent);
            }
            let newColumn = slideTiles(column.reverse()).reverse();
            for (let j = 0; j < boardSize; j++) {
                board[i + j * boardSize].textContent = newColumn[j];
            }
        }
    }

    function moveLeft() {
        for (let i = 0; i < boardSize; i++) {
            let row = [];
            for (let j = 0; j < boardSize; j++) {
                row.push(board[i * boardSize + j].textContent);
            }
            let newRow = slideTiles(row);
            for (let j = 0; j < boardSize; j++) {
                board[i * boardSize + j].textContent = newRow[j];
            }
        }
    }

    function moveRight() {
        for (let i = 0; i < boardSize; i++) {
            let row = [];
            for (let j = 0; j < boardSize; j++) {
                row.push(board[i * boardSize + j].textContent);
            }
            let newRow = slideTiles(row.reverse()).reverse();
            for (let j = 0; j < boardSize; j++) {
                board[i * boardSize + j].textContent = newRow[j];
            }
        }
    }

    function slideTiles(tiles) {
        let newTiles = tiles.filter(tile => tile);
        for (let i = 0; i < newTiles.length - 1; i++) {
            if (newTiles[i] === newTiles[i + 1]) {
                newTiles[i] = (parseInt(newTiles[i]) * 2).toString();
                newTiles[i + 1] = '';
            }
        }
        newTiles = newTiles.filter(tile => tile);
        while (newTiles.length < boardSize) {
            newTiles.push('');
        }
        return newTiles;
    }

    buttons.up.addEventListener('click', () => move('up'));
    buttons.down.addEventListener('click', () => move('down'));
    buttons.left.addEventListener('click', () => move('left'));
    buttons.right.addEventListener('click', () => move('right'));

    document.addEventListener('keydown', (e) => {
        switch (e.key) {
            case 'w': move('up'); break;
            case 's': move('down'); break;
            case 'a': move('left'); break;
            case 'd': move('right'); break;
        }
    });

    initBoard();
});
相关推荐
逐·風2 小时前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
Devil枫3 小时前
Vue 3 单元测试与E2E测试
前端·vue.js·单元测试
尚梦4 小时前
uni-app 封装刘海状态栏(适用小程序, h5, 头条小程序)
前端·小程序·uni-app
GIS程序媛—椰子4 小时前
【Vue 全家桶】6、vue-router 路由(更新中)
前端·vue.js
前端青山4 小时前
Node.js-增强 API 安全性和性能优化
开发语言·前端·javascript·性能优化·前端框架·node.js
PandaQue5 小时前
《怪物猎人:荒野》游戏可以键鼠直连吗
游戏
毕业设计制作和分享5 小时前
ssm《数据库系统原理》课程平台的设计与实现+vue
前端·数据库·vue.js·oracle·mybatis
从兄6 小时前
vue 使用docx-preview 预览替换文档内的特定变量
javascript·vue.js·ecmascript
清灵xmf7 小时前
在 Vue 中实现与优化轮询技术
前端·javascript·vue·轮询
大佩梨7 小时前
VUE+Vite之环境文件配置及使用环境变量
前端