Skip to content
The Chat Archive
qwq-32b LMArena Human Preference 140K

可以幫我用javascript設計一個貪吃蛇遊戲嗎

  1. User

    可以幫我用javascript設計一個貪吃蛇遊戲嗎

  2. Assistant

    以下是用 JavaScript 設計一個基礎的貪吃蛇遊戲的完整代碼,包含 HTML、CSS 和 JavaScript 程式碼,可以直接在瀏覽器中運行:


    完整代碼:

    <!DOCTYPE html>
    <html>
    <head>
        <title>貪吃蛇遊戲</title>
        <style>
            canvas {
                border: 2px solid #000;
                background-color: #eee;
            }
        </style>
    </head>
    <body>
        <canvas id="snakeCanvas" width="400" height="400"></canvas>
        <script>
            const canvas = document.getElementById('snakeCanvas');
            const ctx = canvas.getContext('2d');
            const size = 20; // 每個方塊的大小
            const width = canvas.width / size; // 縱向格數
            const height = canvas.height / size; // 橫向格數
    
            let snake = [{x: 10, y: 10}]; // 蛇的初始位置
            let food = {x: 5, y: 5}; // 食物初始位置
            let direction = 'right'; // 初始移動方向
            let score = 0; // 分數
            let gameRunning = true; // 遊戲是否進行中
    
            // 生成新食物
            function generateFood() {
                food = {
                    x: Math.floor(Math.random() * width),
                    y: Math.floor(Math.random() * height)
                };
                // 確保食物不會出現在蛇身上
                snake.forEach(part => {
                    if (part.x === food.x && part.y === food.y) {
                        generateFood();
                    }
                });
            }
    
            // 繪製畫面
            function draw() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
    
                // 繪製蛇
                snake.forEach(part => {
                    ctx.fillStyle = part === snake[0] ? '#0f0' : '#00f';
                    ctx.fillRect(part.x * size, part.y * size, size, size);
                });
    
                // 繪製食物
                ctx.fillStyle = '#f00';
                ctx.fillRect(food.x * size, food.y * size, size, size);
    
                // 顯示分數
                ctx.font = "15px Arial";
                ctx.fillStyle = "#000";
                ctx.fillText("Score: " + score, 10, 20);
            }
    
            // 移動邏輯
            function move() {
                const head = { 
                    x: snake[0].x, 
                    y: snake[0].y 
                };
    
                // 根據方向移動
                switch(direction) {
                    case 'right':
                        head.x++;
                        break;
                    case 'left':
                        head.x--;
                        break;
                    case 'up':
                        head.y--;
                        break;
                    case 'down':
                        head.y++;
                        break;
                }
    
                // 檢查碰撞
                if (
                    head.x < 0 || 
                    head.x >= width || 
                    head.y < 0 || 
                    head.y >= height ||
                    snake.some(part => part.x === head.x && part.y === head.y) // 撞到自己
                ) {
                    gameRunning = false;
                    return;
                }
    
                // 新的頭部加入
                snake.unshift(head);
    
                // 如果吃到食物
                if (head.x === food.x && head.y === food.y) {
                    score++;
                    generateFood();
                } else {
                    // 移除尾部
                    snake.pop();
                }
            }
    
            // 處理方向鍵輸入
            document.addEventListener('keydown', function(e) {
                const key = e.key;
                const opposite = {
                    'right': 'left',
                    'left': 'right',
                    'up': 'down',
                    'down': 'up'
                };
    
                if (key in opposite && opposite[key] !== direction) {
                    direction = key;
                }
            });
    
            // 遊戲循環
            function gameLoop() {
                if (!gameRunning) {
                    ctx.font = "30px Arial";
                    ctx.fillText("遊戲結束!得分:" + score, 50, canvas.height / 2);
                    return;
                }
    
                move();
                draw();
                requestAnimationFrame(gameLoop);
            }
    
            // 開始遊戲
            generateFood();
            gameLoop();
        </script>
    </body>
    </html>
    

    遊戲說明:

    1. 畫布設定:

      • 使用 <canvas> 元素建立遊戲畫布,預設尺寸為 400x400。
      • 每個方塊大小為 20x20,因此遊戲場景會被劃分為 20x20 的格子。
    2. 蛇的結構:

      • snake 是一個陣列,每個元素代表蛇的身體部位(頭部在索引 0)。
      • 頭部顏色為綠色,身體為藍色。
    3. 食物生成:

      • 食物會隨機出現在畫布內,並確保不會出現在蛇的身上。
    4. 移動邏輯:

      • 按方向鍵控制蛇移動。
      • 當蛇吃到食物時,蛇會增長且分數增加。
      • 如果蛇撞到邊界或自己,遊戲結束。
    5. 遊戲循環:

      • 使用 requestAnimationFrame 繼續更新遊戲狀態和繪製畫面。

    如何運行:

    1. 將上述代碼複製到 .html 檔案中。
    2. 在瀏覽器中打開該檔案即可運行遊戲。

    可調整的參數:

    1. 畫布大小:

      const canvas = document.getElementById('snakeCanvas');
      canvas.width = 600; // 修改寬度
      canvas.height = 600; // 修改高度
      
    2. 方塊大小:

      const size = 25; // 調整方塊大小(建議整數)
      
    3. 初始分數與蛇長度:

      let snake = [{x: 10, y: 10}, {x: 9, y: 10}]; // 增加初始蛇長度
      let score = 5; // 設定初始分數
      

    擴展建議:

    1. 增加速度:

      let speed = 100; // 每 100ms 移動一次
      let lastTime = 0;
      function gameLoop(currentTime) {
          if (currentTime - lastTime > speed) {
              move();
              draw();
              lastTime = currentTime;
          }
          requestAnimationFrame(gameLoop);
      }
      
    2. 難度提升:

      • 隨著分數增加,加快遊戲速度:
        if (score % 5 === 0) speed -= 10; // 每 5 分加速一次
        
    3. 新增障礙物:

      • 在畫布中隨機生成障礙物,增加挑戰性。

    如果需要進一步調整或有其他問題,可以隨時告訴我! 😊

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.