|
|
好的,小朋友!我们可以在游戏过程中添加背景音乐,让你的贪吃蛇游戏更有趣。我们将使用一个音频文件来作为背景音乐,并在游戏开始时播放它,游戏结束时暂停它。
假设你有一个叫做 `background.mp3` 的背景音乐文件,可以将其放置在与 `index.html` 和 `script.js` 同一个目录中。接下来,我们将使用一个函数来播放和控制这个背景音乐。
### 第一步:准备背景音乐文件
确保 `background.mp3` 文件放置在项目目录中。
### 第二步:修改 JavaScript 代码
在你的 `script.js` 文件中,添加一个函数来播放背景音乐,并在游戏开始和结束时进行相应的操作。
#### 修改后的 `script.js` 文件:
- const canvas = document.getElementById('gameCanvas');
- const ctx = canvas.getContext('2d');
- let snake = [{x: 150, y: 150}, {x: 140, y: 150}, {x: 130, y: 150}];
- let food = { x: 0, y: 0 };
- let dx = 10;
- let dy = 0;
- let score = 0;
- let gameOver = false;
- // 创建音效对象
- const eatSound = new Audio('eat.mp3');
- // 创建背景音乐对象
- const backgroundMusic = new Audio('background.mp3');
- backgroundMusic.loop = true; // 设置循环播放
- document.addEventListener("keydown", changeDirection);
- function randomFoodPosition() {
- const x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
- const y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
- return { x, y };
- }
- function clearCanvas() {
- ctx.fillStyle = "white";
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- }
- function drawSnake() {
- snake.forEach(drawSnakePart);
- }
- function drawSnakePart(snakePart) {
- ctx.fillStyle = 'lightgreen';
- ctx.strokeStyle = 'darkgreen';
- ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
- ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
- }
- function drawFood() {
- ctx.fillStyle = 'red';
- ctx.fillRect(food.x, food.y, 10, 10);
- }
- function moveSnake() {
- const head = { x: snake[0].x + dx, y: snake[0].y + dy };
- if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || collision(head)) {
- gameOver = true;
- return;
- }
- snake.unshift(head);
- if (head.x === food.x && head.y === food.y) {
- score++;
- food = randomFoodPosition();
- playEatSound(); // 播放音效
- } else {
- snake.pop();
- }
- }
- function collision(head) {
- for (let i = 1; i < snake.length; i++) {
- if (snake[i].x === head.x && snake[i].y === head.y) {
- return true;
- }
- }
- return false;
- }
- // 播放吃食物的音效
- function playEatSound() {
- eatSound.play();
- }
- // 播放背景音乐
- function playBackgroundMusic() {
- backgroundMusic.play();
- }
- // 停止背景音乐
- function stopBackgroundMusic() {
- backgroundMusic.pause();
- backgroundMusic.currentTime = 0; // 重置音乐到开头
- }
- function main() {
- if (gameOver) {
- displayGameOver();
- return;
- }
- setTimeout(function onTick() {
- clearCanvas();
- drawFood();
- moveSnake();
- drawSnake();
- main();
- }, 100);
- }
- function changeDirection(event) {
- const LEFT_KEY = 37;
- const RIGHT_KEY = 39;
- const UP_KEY = 38;
- const DOWN_KEY = 40;
- const keyPressed = event.keyCode;
- const goingUp = dy === -10;
- const goingDown = dy === 10;
- const goingRight = dx === 10;
- const goingLeft = dx === -10;
- if (keyPressed === LEFT_KEY && !goingRight) {
- dx = -10;
- dy = 0;
- }
- if (keyPressed === UP_KEY && !goingDown) {
- dx = 0;
- dy = -10;
- }
- if (keyPressed === RIGHT_KEY && !goingLeft) {
- dx = 10;
- dy = 0;
- }
- if (keyPressed === DOWN_KEY && !goingUp) {
- dx = 0;
- dy = 10;
- }
- }
- function displayGameOver() {
- ctx.fillStyle = "black";
- ctx.font = "30px Arial";
- ctx.fillText("游戏结束!", canvas.width / 2 - 75, canvas.height / 2 - 20);
- ctx.fillText("得分: " + score, canvas.width / 2 - 50, canvas.height / 2 + 20);
- document.getElementById('startButton').style.display = 'block';
- stopBackgroundMusic(); // 停止背景音乐
- }
- function startGame() {
- snake = [{x: 150, y: 150}, {x: 140, y: 150}, {x: 130, y: 150}];
- score = 0;
- dx = 10;
- dy = 0;
- gameOver = false;
- food = randomFoodPosition();
- document.getElementById('startButton').style.display = 'none';
- playBackgroundMusic(); // 播放背景音乐
- main();
- }
- food = randomFoodPosition();
- main();
复制代码
### 第三步:修改 HTML 代码
如果你还没有一个 "开始游戏" 按钮,请确保在 `index.html` 中添加它:
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <title>贪吃蛇游戏</title>
- <style>
- body {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- height: 100vh;
- background-color: #e0e0e0;
- margin: 0;
- }
- h1 {
- margin-bottom: 20px;
- }
- #gameContainer {
- display: flex;
- flex-direction: column;
- align-items: center;
- }
- canvas {
- border: 1px solid black;
- background-color: #f5f5f5;
- }
- #startButton {
- display: none; /* 默认隐藏 */
- padding: 10px 20px;
- font-size: 20px;
- margin-top: 20px;
- cursor: pointer;
- background-color: #4CAF50; /* 绿色按钮 */
- color: white;
- border: none;
- border-radius: 5px;
- }
- #startButton:hover {
- background-color: #ADD8E6; /* 浅蓝色 */
- }
- #gameOverText {
- font-size: 24px;
- color: red;
- text-align: center;
- margin-top: 20px;
- display: none; /* 默认隐藏 */
- }
- .hidden {
- display: none;
- }
- </style>
- </head>
- <body>
- <h1>贪吃蛇游戏</h1>
- <div id="gameContainer">
- <canvas id="gameCanvas" width="400" height="400"></canvas>
- <div id="gameOverText" class="hidden">
- <p>很遗憾!游戏结束</p>
- <p>得分: <span id="score">0</span></p>
- </div>
- <button id="startButton" onclick="startGame()">开始游戏</button>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
### 解释修改内容:
1. **创建背景音乐对象**:
- const backgroundMusic = new Audio('background.mp3');
- backgroundMusic.loop = true; // 设置循环播放
复制代码
这行代码创建了一个新的音频对象,并载入 `background.mp3` 文件,同时设置了循环播放。
2. **播放背景音乐函数**:
- function playBackgroundMusic() {
- backgroundMusic.play();
- }
复制代码
3. **停止背景音乐函数**:
- function stopBackgroundMusic() {
- backgroundMusic.pause();
- backgroundMusic.currentTime = 0; // 重置音乐到开头
- }
复制代码
4. **在游戏开始时播放背景音乐**:
- function startGame() {
- // ... 其他代码
- playBackgroundMusic(); // 播放背景音乐
- main();
- }
复制代码
5. **在游戏结束时停止背景音乐**:
- function displayGameOver() {
- // ... 其他代码
- stopBackgroundMusic(); // 停止背景音乐
- }
复制代码
通过这些修改,你的游戏在开始时会播放背景音乐,并在游戏结束时停止。如果有任何问题或需要进一步帮助,请随时告诉我哦! |
|