前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >js+jquery实现贪吃蛇经典小游戏

js+jquery实现贪吃蛇经典小游戏

原创
作者头像
恩爸编程
发布2024-11-27 22:59:11
发布2024-11-27 22:59:11
11800
代码可运行
举报
运行总次数:0
代码可运行

项目只使用到了html,css,js,jquery技术点,没有使用游戏框架,下载本地直接双击index.html 运行即可体验游戏效果。

项目展示

进入游戏

游戏开始

游戏暂停

html文件

代码语言:html
复制
<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>贪吃蛇游戏</title>

    <link rel="stylesheet" href="style.css">

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>

    <div class="container">

        <div class="game-wrapper">

            <h1>贪吃蛇游戏</h1>

            <div class="game-info">

                <div class="score-container">

                    <div class="score">得分: <span id="score">0</span></div>

                    <div class="high-score">最高分: <span id="highScore">0</span></div>

                </div>

                <button id="startBtn">开始游戏</button>

            </div>

            <div class="game-board-wrapper">

                <div id="gameBoard"></div>

            </div>

            <div class="controls-info">

                <p>使用方向键 ← ↑ → ↓ 控制蛇的移动</p>

                <p>按空格键 <span class="key-space">Space</span> 暂停/继续游戏</p>

            </div>

        </div>

    </div>

    <script src="game.js"></script>

</body>

</html> 

CSS文件

代码语言:css
复制
\* {

    margin: 0;

    padding: 0;

    box-sizing: border-box;

}



body {

    background: linear-gradient(135deg, #1a1a2e, #16213e);

    min-height: 100vh;

    display: flex;

    justify-content: center;

    align-items: center;

    color: #fff;

    font-family: Arial, sans-serif;

}



.container {

    width: 100%;

    max-width: 800px;

    padding: 20px;

}



.game-wrapper {

    background: rgba(255, 255, 255, 0.1);

    border-radius: 20px;

    padding: 30px;

    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);

    backdrop-filter: blur(4px);

    border: 1px solid rgba(255, 255, 255, 0.18);

}



h1 {

    text-align: center;

    margin-bottom: 30px;

    font-size: 2.5em;

    color: #fff;

    text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);

}



.game-info {

    display: flex;

    justify-content: space-between;

    align-items: center;

    margin-bottom: 20px;

}



.score-container {

    font-size: 1.2em;

}



.score, .high-score {

    margin: 5px 0;

}



#score, #highScore {

    color: #4CAF50;

    font-weight: bold;

}



#startBtn {

    background: #4CAF50;

    color: white;

    border: none;

    padding: 12px 30px;

    border-radius: 25px;

    font-size: 1.1em;

    cursor: pointer;

    transition: all 0.3s ease;

    box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);

}



#startBtn:hover {

    background: #45a049;

    transform: translateY(-2px);

}



.game-board-wrapper {

    display: flex;

    justify-content: center;

    margin: 20px 0;

}



#gameBoard {

    width: 600px;

    height: 600px;

    border-radius: 10px;

    background: rgba(255, 255, 255, 0.05);

    border: 2px solid rgba(255, 255, 255, 0.1);

    position: relative;

}



.snake-body {

    width: 20px;

    height: 20px;

    background: #4CAF50;

    position: absolute;

    border-radius: 4px;

}



.snake-body.head {

    background: #66bb6a;

    box-shadow: 0 0 15px rgba(76, 175, 80, 0.7);

}



.food {

    width: 20px;

    height: 20px;

    background: #ff4444;

    position: absolute;

    border-radius: 50%;

    box-shadow: 0 0 15px rgba(255, 68, 68, 0.7);

}



.controls-info {

    text-align: center;

    margin-top: 20px;

    color: rgba(255, 255, 255, 0.7);

    font-size: 0.9em;

    line-height: 1.6;

}



.controls-info p {

    margin: 5px 0;

}



.key-space {

    display: inline-block;

    padding: 2px 8px;

    background: rgba(255, 255, 255, 0.1);

    border: 1px solid rgba(255, 255, 255, 0.2);

    border-radius: 4px;

    margin: 0 3px;

}



@media (max-width: 768px) {

    #gameBoard {

        width: 300px;

        height: 300px;

    }

    

    .snake-body, .food {

        width: 10px;

        height: 10px;

    }

}



.pause-text {

    position: absolute;

    top: 50%;

    left: 50%;

    transform: translate(-50%, -50%);

    font-size: 2em;

    color: #fff;

    background: rgba(0, 0, 0, 0.7);

    padding: 20px 40px;

    border-radius: 10px;

    z-index: 100;

    animation: pulse 1.5s infinite;

}



@keyframes pulse {

    0% { opacity: 0.6; }

    50% { opacity: 1; }

    100% { opacity: 0.6; }

} 

js文件

代码语言:javascript
代码运行次数:0
复制
$(document).ready(function() {

    // 游戏配置

    const boardSize = 600;

    const cellSize = 20;

    const gridSize = boardSize / cellSize;

    

    // 游戏状态

    let snake = [];

    let food = {};

    let direction = 'right';

    let gameLoop;

    let score = 0;

    let highScore = localStorage.getItem('highScore') || 0;

    let isGameRunning = false;

    

    // 添加暂停状态变量

    let isPaused = false;

    let savedInterval = null;

    

    // 显示最高分

    $('#highScore').text(highScore);



    // 初始化蛇的位置

    function initSnake() {

        snake = [

            {x: 6, y: 10},

            {x: 5, y: 10},

            {x: 4, y: 10}

        ];

    }



    // 生成食物

    function generateFood() {

        while (true) {

            food = {

                x: Math.floor(Math.random() \* gridSize),

                y: Math.floor(Math.random() \* gridSize)

            };

            

            // 确保食物不会生成在蛇身上

            let foodOnSnake = false;

            for (let body of snake) {

                if (body.x === food.x && body.y === food.y) {

                    foodOnSnake = true;

                    break;

                }

            }

            if (!foodOnSnake) break;

        }

    }



    // 绘制游戏画面

    function draw() {

        $('#gameBoard').empty();

        

        // 绘制蛇

        snake.forEach((segment, index) => {

            const snakeElement = $('<div>')

                .addClass('snake-body')

                .css({

                    left: segment.x \* cellSize + 'px',

                    top: segment.y \* cellSize + 'px'

                });

            

            if (index === 0) {

                snakeElement.addClass('head');

            }

            

            $('#gameBoard').append(snakeElement);

        });

        

        // 绘制食物

        $('#gameBoard').append(

            $('<div>')

                .addClass('food')

                .css({

                    left: food.x \* cellSize + 'px',

                    top: food.y \* cellSize + 'px'

                })

        );

    }



    // 移动蛇

    function moveSnake() {

        const head = {x: snake[0].x, y: snake[0].y};

        

        switch(direction) {

            case 'up': head.y--; break;

            case 'down': head.y++; break;

            case 'left': head.x--; break;

            case 'right': head.x++; break;

        }

        

        // 检查是否撞墙

        if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize) {

            gameOver();

            return;

        }

        

        // 检查是否撞到自己

        for (let body of snake) {

            if (head.x === body.x && head.y === body.y) {

                gameOver();

                return;

            }

        }

        

        snake.unshift(head);

        

        // 检查是否吃到食物

        if (head.x === food.x && head.y === food.y) {

            score += 10;

            $('#score').text(score);

            if (score > highScore) {

                highScore = score;

                localStorage.setItem('highScore', highScore);

                $('#highScore').text(highScore);

            }

            generateFood();

        } else {

            snake.pop();

        }

        

        draw();

    }



    // 游戏结束

    function gameOver() {

        clearInterval(gameLoop);

        alert('游戏结束!得分:' + score);

        isGameRunning = false;

        isPaused = false;

        $('#startBtn').text('重新开始');

        $('.pause-text').remove();

    }



    // 开始游戏

    function startGame() {

        if (isGameRunning) return;

        

        isGameRunning = true;

        isPaused = false;

        score = 0;

        $('#score').text(score);

        direction = 'right';

        $('#startBtn').text('游戏中...');

        

        initSnake();

        generateFood();

        draw();

        

        if (gameLoop) clearInterval(gameLoop);

        gameLoop = setInterval(moveSnake, 150);

    }



    // 添加暂停函数

    function togglePause() {

        if (!isGameRunning) return;

        

        if (isPaused) {

            // 继续游戏

            isPaused = false;

            gameLoop = setInterval(moveSnake, 150);

            $('#startBtn').text('游戏中...');

            // 移除暂停提示

            $('.pause-text').remove();

        } else {

            // 暂停游戏

            isPaused = true;

            clearInterval(gameLoop);

            $('#startBtn').text('已暂停');

            // 添加暂停提示

            $('#gameBoard').append(

                $('<div>')

                    .addClass('pause-text')

                    .text('游戏暂停')

            );

        }

    }



    // 键盘控制

    $(document).keydown(function(e) {

        // 防止方向键和空格键滚动页面

        if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {

            e.preventDefault();

        }

        

        // 空格键控制暂停

        if (e.keyCode === 32) { // 空格键

            togglePause();

            return;

        }

        

        // 游戏暂停时不响应方向键

        if (!isGameRunning || isPaused) return;

        

        switch(e.keyCode) {

            case 38: // 上

                if (direction !== 'down') direction = 'up';

                break;

            case 40: // 下

                if (direction !== 'up') direction = 'down';

                break;

            case 37: // 左

                if (direction !== 'right') direction = 'left';

                break;

            case 39: // 右

                if (direction !== 'left') direction = 'right';

                break;

        }

    });



    // 绑定开始按钮事件

    $('#startBtn').click(startGame);

}); 

总结

可以直接下载代码到本地,双击index.html文件即可运行查看效果并体验游戏。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 项目展示
    • 进入游戏
    • 游戏开始
    • 游戏暂停
    • html文件
    • CSS文件
    • js文件
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档