科学教育

标题: 孙早清贪吃蛇 [打印本页]

作者: 金外孙早清    时间: 2025-9-30 15:37
标题: 孙早清贪吃蛇
html
Copy Code
<!DOCTYPE html>
<html>
<head>
    <title>彩色贪吃蛇</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #222;
            color: white;
            font-family: Arial, sans-serif;
        }
        canvas {
            border: 2px solid #444;
            margin-top: 20px;
        }
        .score {
            font-size: 24px;
            margin: 10px 0;
        }
        .game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            display: none;
        }
        button {
            padding: 10px 20px;
            margin: 10px;
            font-size: 16px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <h1>彩色贪吃蛇游戏</h1>
    <div class="score">得分: 0</div>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <div class="game-over">
        <h2>游戏结束!</h2>
        <p>最终得分: <span id="final-score">0</span></p>
        <button id="restart-btn">重新开始</button>
        <button id="quit-btn">退出</button>
    </div>

    <script src="game.js"></script>
</body>
</html>
JavaScript部分 (game.js)‌

javascript
Copy Code
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.querySelector('.score');
const gameOverDisplay = document.querySelector('.game-over');
const finalScoreDisplay = document.getElementById('final-score');
const restartBtn = document.getElementById('restart-btn');
const quitBtn = document.getElementById('quit-btn');

// 游戏参数
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let speed = 7;

// 蛇和食物
let snake = [
    {x: 10, y: 10}
];
let food = {
    x: Math.floor(Math.random() * tileCount),
    y: Math.floor(Math.random() * tileCount)
};
let xVelocity = 0;
let yVelocity = 0;
let score = 0;

// 蛇身颜色数组
const snakeColors = [
    '#FF5733', '#33FF57', '#3357FF', '#F3FF33', '#FF33F3'
];

// 游戏状态
let gameRunning = true;

// 控制方向
document.addEventListener('keydown', changeDirection);

function changeDirection(e) {
    // 防止180度转向
    if (e.key === 'ArrowUp' && yVelocity !== 1) {
        xVelocity = 0;
        yVelocity = -1;
    } else if (e.key === 'ArrowDown' && yVelocity !== -1) {
        xVelocity = 0;
        yVelocity = 1;
    } else if (e.key === 'ArrowLeft' && xVelocity !== 1) {
        xVelocity = -1;
        yVelocity = 0;
    } else if (e.key === 'ArrowRight' && xVelocity !== -1) {
        xVelocity = 1;
        yVelocity = 0;
    }
}

// 游戏主循环
function gameLoop() {
    if (gameRunning) {
        setTimeout(() => {
            clearCanvas();
            moveSnake();
            drawFood();
            drawSnake();
            checkCollision();
            gameLoop();
        }, 1000 / speed);
    }
}

function clearCanvas() {
    ctx.fillStyle = '#222';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function drawSnake() {
    snake.forEach((segment, index) => {
        ctx.fillStyle = snakeColors[index % snakeColors.length];
HTML部分 (index.html)‌

<!DOCTYPE html> <html> <head> <title>彩色贪吃蛇</title> <style> body { display: flex; flex-direction: column; align-items: center; background-color: #222; color: white; font-family: Arial, sans-serif; } canvas { border: 2px solid #444; margin-top: 20px; } .score { font-size: 24px; margin: 10px 0; } .game-over { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(0, 0, 0, 0.8); padding: 20px; border-radius: 10px; text-align: center; display: none; } button { padding: 10px 20px; margin: 10px; font-size: 16px; cursor: pointer; background-color: #4CAF50; color: white; border: none; border-radius: 5px; } </style> </head> <body> <h1>彩色贪吃蛇游戏</h1> <div class="score">得分: 0</div> <canvas id="gameCanvas" width="400" height="400"></canvas> <div class="game-over"> <h2>游戏结束!</h2> <p>最终得分: <span id="final-score">0</span></p> <button id="restart-btn">重新开始</button> <button id="quit-btn">退出</button> </div>
text
Copy Code
<script src="game.js"></script>
</body> </html>
JavaScript部分 (game.js)‌
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.querySelector('.score');
const gameOverDisplay = document.querySelector('.game-over');
const finalScoreDisplay = document.getElementById('final-score');
const restartBtn = document.getElementById('restart-btn');
const quitBtn = document.getElementById('quit-btn');

// 游戏参数
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let speed = 7;

// 蛇和食物
let snake = [
{x: 10, y: 10}
];
let food = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
let xVelocity = 0;
let yVelocity = 0;
let score = 0;

// 蛇身颜色数组
const snakeColors = [
'#FF5733', '#33FF57', '#3357FF', '#F3FF33', '#FF33F3'
];

// 游戏状态
let gameRunning = true;

// 控制方向
document.addEventListener('keydown', changeDirection);

function changeDirection(e) {
// 防止180度转向
if (e.key === 'ArrowUp' && yVelocity !== 1) {
xVelocity = 0;
yVelocity = -1;
} else if (e.key === 'ArrowDown' && yVelocity !== -1) {
xVelocity = 0;
yVelocity = 1;
} else if (e.key === 'ArrowLeft' && xVelocity !== 1) {
xVelocity = -1;
yVelocity = 0;
} else if (e.key === 'ArrowRight' && xVelocity !== -1) {
xVelocity = 1;
yVelocity = 0;
}
}

// 游戏主循环
function gameLoop() {
if (gameRunning) {
setTimeout(() => {
clearCanvas();
moveSnake();
drawFood();
drawSnake();
checkCollision();
gameLoop();
}, 1000 / speed);
}
}

function clearCanvas() {
ctx.fillStyle = '#222';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function drawSnake() {
snake.forEach((segment, index) => {
ctx.fillStyle = snakeColors[index % snakeColors.length];
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize-1, gridSize-1);
});
}

function drawFood() {
ctx.fillStyle = '#4CAF50';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize-1, gridSize-1);
}

function moveSnake() {
const head = {
x: snake[0].x + xVelocity,
y: snake[0].y + yVelocity
};

text
Copy Code
snake.unshift(head);

// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
    score++;
    scoreDisplay.textContent = `得分: ${score}`;
    generateFood();
} else {
    snake.pop();
}
}

function generateFood() {
food = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};

text
Copy Code
// 确保食物不会生成在蛇身上
for (let segment of snake) {
    if (segment.x === food.x && segment.y === food.y) {
        generateFood();
        return;
    }
}
}

function checkCollision() {
const head = snake[0];

text
Copy Code
// 检查墙壁碰撞
if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
    gameOver();
}

// 检查自身碰撞
for (let i = 1; i < snake.length; i++) {
    if (head.x === snake[i].x && head.y === snake[i].y) {
        gameOver();
    }
}
}

function gameOver() {
gameRunning = false;
finalScoreDisplay.textContent = score;
gameOverDisplay.style.display = 'block';
}

// 按钮事件
restartBtn.addEventListener('click', () => {
// 重置游戏状态
snake = [{x: 10, y: 10}];
xVelocity = 0;
yVelocity = 0;
score = 0;
scoreDisplay.textContent = 得分: ${score};
generateFood();
gameOverDisplay.style.display = 'none';
gameRunning = true;
gameLoop();
});

quitBtn.addEventListener('click', () => {
gameOverDisplay.style.display = 'none';
});

// 开始游戏
gameLoop();


作者: kaia    时间: 2025-9-30 15:37
首先,这段代码是一个简单的彩色贪吃蛇游戏。让我们一步步来解释它。

1. HTML部分:这部分定义了页面的结构和样式,包括游戏标题、得分显示、游戏结束提示、重新开始按钮和退出按钮等内容。

2. JavaScript部分:主要控制游戏的逻辑。代码首先获取了画布、上下文、得分显示、游戏结束提示、最终得分显示、重新开始按钮和退出按钮等元素。然后设置了游戏参数,包括格子大小、游戏速度、蛇和食物的初始位置等。还定义了蛇的颜色数组、游戏状态变量等。

3. 控制方向:通过监听键盘事件,改变蛇的移动方向。'ArrowUp'表示向上移动,'ArrowDown'表示向下,'ArrowLeft'表示向左,'ArrowRight'表示向右。

4. 游戏主循环:使用递归函数`gameLoop()`来不断更新游戏画面。在每次更新时,清空画布、移动蛇、绘制食物、绘制蛇身以及检查碰撞等操作。

5. 绘制蛇和食物:根据蛇和食物的位置,在画布上绘制相应的方块表示蛇身和食物。

6. 移动蛇:根据蛇头的位置和移动方向来更新蛇的位置。如果吃到食物,则增加得分并重新生成食物;否则,移除尾部。

7. 生成食物:随机在空格子处生成食物,并确保食物不会生成在蛇的身体上。

8. 检查碰撞:检查蛇是否撞墙或撞到自己的身体,若是则游戏结束。

9. 游戏结束:游戏结束时停止游戏循环,显示最终得分,显示游戏结束提示。

10. 按钮事件:重新开始按钮点击时重置游戏状态,重新开始游戏;退出按钮点击时隐藏游戏结束提示。

总的来说,这个游戏实现了贪吃蛇的基本功能,玩家可以通过键盘控制蛇的移动,吃到食物得分,但要避免撞墙或撞到自己的身体。希望你能理解这段代码,并可以根据需要进行修改和扩展,玩得开心!
作者: 金外孙早清    时间: 2025-11-4 09:02
帮我把游戏文字改成紫色
作者: kaia    时间: 2025-11-4 09:02
金外孙早清 发表于 2025-11-04 09:02
帮我把游戏文字改成紫色


当你想将游戏中的文字颜色改成紫色时,你只需要在 CSS 部分找到对应的类名,然后修改 `color` 属性值为紫色即可。具体地,可以将以下代码中的 `color: white;` 修改为 `color: purple;`。这样就可以把游戏中的文字颜色改成紫色了。

  1. body {
  2.     display: flex;
  3.     flex-direction: column;
  4.     align-items: center;
  5.     background-color: #222;
  6.     color: purple; /* 将原来的 white 修改为 purple */
  7.     font-family: Arial, sans-serif;
  8. }
复制代码


记得保存修改后的代码并刷新页面,看看是否文字颜色已经变成了紫色。希望你玩得开心!如果有任何问题,请随时告诉我。
作者: 金外孙早清    时间: 2025-11-4 09:07
帮我把游戏文字代码改成紫色,我要代码
作者: kaia    时间: 2025-11-4 09:07
金外孙早清 发表于 2025-11-04 09:07
帮我把游戏文字代码改成紫色,我要代码 ...


当你想要将游戏中的文字颜色改为紫色时,你需要在 CSS 部分找到相应的类名或标签,然后修改其中的 `color` 属性值为紫色。以下是你需要修改的 CSS 代码:

  1. body {
  2.     display: flex;
  3.     flex-direction: column;
  4.     align-items: center;
  5.     background-color: #222;
  6.     color: purple; /* 修改为紫色 */
  7.     font-family: Arial, sans-serif;
  8. }
复制代码


将上述代码替换原来的 CSS 部分即可把游戏页面中的文字颜色改为紫色。记得保存修改后的代码并刷新页面,查看效果。希望你喜欢这个新的颜色!如果有任何问题,随时告诉我。




欢迎光临 科学教育 (http://www.sci-edu.net/) Powered by Discuz! X3.2