原生html贪吃蛇?

bash 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全屏贪吃蛇游戏</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow: hidden;
        }
        #game-container {
            width: 100%;
            height: 100%;
            background-color: #f0f0f0;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        #game-board {
            background-color: #e0e0e0;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .snake-part {
            background-color: #4CAF50;
            border-radius: 50%;
            position: absolute;
        }
        .food {
            background-color: #FF5722;
            border-radius: 50%;
            position: absolute;
        }
        #score {
            font-size: 24px;
            margin-top: 20px;
        }
        #start-button {
            font-size: 18px;
            padding: 10px 20px;
            margin-top: 20px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="game-container">
        <div id="game-board"></div>
        <div id="score">得分: 0</div>
        <button id="start-button">开始游戏</button>
    </div>
    <script>
        const gameBoard = document.getElementById('game-board');
        const scoreElement = document.getElementById('score');
        const startButton = document.getElementById('start-button');
        let snake, food, direction, score, gameInterval;
        let cellSize, boardWidth, boardHeight;

        function initGame() {
            cellSize = Math.floor(Math.min(window.innerWidth, window.innerHeight) / 40);
            boardWidth = Math.floor(window.innerWidth / cellSize);
            boardHeight = Math.floor(window.innerHeight / cellSize);
            
            gameBoard.style.width = boardWidth * cellSize + 'px';
            gameBoard.style.height = boardHeight * cellSize + 'px';

            snake = [{x: Math.floor(boardWidth / 2), y: Math.floor(boardHeight / 2)}];
            direction = 'right';
            score = 0;
            generateFood();
            updateScore();
        }

        function startGame() {
            if (gameInterval) clearInterval(gameInterval);
            initGame();
            gameInterval = setInterval(gameLoop, 100);
            startButton.textContent = '重新开始';
            // 确保游戏开始时绘制初始状态
            drawGame();
        }

        function gameLoop() {
            moveSnake();
            if (checkCollision()) {
                endGame();
                return;
            }
            if (checkFoodCollision()) {
                score++;
                updateScore();
                generateFood();
            } else {
                snake.pop();
            }
            drawGame();
        }

        function drawGame() {
            gameBoard.innerHTML = '';
            snake.forEach(drawSnakePart);
            drawFood();
        }

        function drawSnakePart(part) {
            const element = createGameElement('snake-part');
            setPosition(element, part);
            gameBoard.appendChild(element);
        }

        function drawFood() {
            const element = createGameElement('food');
            setPosition(element, food);
            gameBoard.appendChild(element);
        }

        function createGameElement(className) {
            const element = document.createElement('div');
            element.className = className;
            element.style.width = cellSize + 'px';
            element.style.height = cellSize + 'px';
            return element;
        }

        function setPosition(element, position) {
            element.style.left = position.x * cellSize + 'px';
            element.style.top = position.y * cellSize + 'px';
        }

        function moveSnake() {
            const head = {...snake[0]};
            switch(direction) {
                case 'up': head.y--; break;
                case 'down': head.y++; break;
                case 'left': head.x--; break;
                case 'right': head.x++; break;
            }
            snake.unshift(head);
        }

        function generateFood() {
            food = {
                x: Math.floor(Math.random() * boardWidth),
                y: Math.floor(Math.random() * boardHeight)
            };
            // 确保食物不会生成在蛇身上
            while (snake.some(part => part.x === food.x && part.y === food.y)) {
                food.x = Math.floor(Math.random() * boardWidth);
                food.y = Math.floor(Math.random() * boardHeight);
            }
        }

        function checkCollision() {
            const head = snake[0];
            return (
                head.x < 0 || head.x >= boardWidth ||
                head.y < 0 || head.y >= boardHeight ||
                snake.slice(1).some(part => part.x === head.x && part.y === head.y)
            );
        }

        function checkFoodCollision() {
            const head = snake[0];
            return food.x === head.x && food.y === head.y;
        }

        function updateScore() {
            scoreElement.textContent = `得分: ${score}`;
        }

        function endGame() {
            clearInterval(gameInterval);
            alert(`游戏结束!你的得分是 ${score}`);
        }

        document.addEventListener('keydown', (event) => {
            switch(event.key) {
                case 'ArrowUp': if (direction !== 'down') direction = 'up'; break;
                case 'ArrowDown': if (direction !== 'up') direction = 'down'; break;
                case 'ArrowLeft': if (direction !== 'right') direction = 'left'; break;
                case 'ArrowRight': if (direction !== 'left') direction = 'right'; break;
            }
        });

        startButton.addEventListener('click', startGame);

        window.addEventListener('resize', () => {
            initGame();
            drawGame();
        });

        // 初始化游戏,但不开始运行
        initGame();
        drawGame();
    </script>
</body>
</html>
相关推荐
Cachel wood23 分钟前
python round四舍五入和decimal库精确四舍五入
java·linux·前端·数据库·vue.js·python·前端框架
学代码的小前端24 分钟前
0基础学前端-----CSS DAY9
前端·css
joan_8528 分钟前
layui表格templet图片渲染--模板字符串和字符串拼接
前端·javascript·layui
还是大剑师兰特1 小时前
什么是尾调用,使用尾调用有什么好处?
javascript·大剑师·尾调用
m0_748236111 小时前
Calcite Web 项目常见问题解决方案
开发语言·前端·rust
Watermelo6171 小时前
详解js柯里化原理及用法,探究柯里化在Redux Selector 的场景模拟、构建复杂的数据流管道、优化深度嵌套函数中的精妙应用
开发语言·前端·javascript·算法·数据挖掘·数据分析·ecmascript
m0_748248941 小时前
HTML5系列(11)-- Web 无障碍开发指南
前端·html·html5
m0_748235611 小时前
从零开始学前端之HTML(三)
前端·html
旭久2 小时前
SpringBoot的Thymeleaf做一个可自定义合并td的pdf表格
pdf·html·springboot
一个处女座的程序猿O(∩_∩)O3 小时前
小型 Vue 项目,该不该用 Pinia 、Vuex呢?
前端·javascript·vue.js