js+jquery實現貪吃蛇經典小遊戲

恩爸编程發表於2024-11-24

專案只使用到了html,css,js,jquery技術點,沒有使用遊戲框架,下載本地直接雙擊index.html 執行即可體驗遊戲效果。

專案展示

進入遊戲

file

遊戲開始

file

遊戲暫停

file

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檔案

* {
    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檔案

$(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檔案即可執行檢視效果並體驗遊戲。

相關文章