原生html贪吃蛇?

2024-07-19 1488阅读

原生html贪吃蛇?

Python


    
    
    全屏贪吃蛇游戏
    
        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;
        }
    


    
        
        得分: 0
        开始游戏
    
    
        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 = boardWidth ||
                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();
    


VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]