|
|
好的,将画布改为透明背景可以使其与背景图片更好地融合。我们只需要调整CSS和JavaScript代码中的一些内容,确保画布的背景是透明的。
### 更新后的完整代码
#### `index.html`
以下是更新后的HTML文件内容:
Snake Game
Snake Game
Start Game
Score: 0
#### `styles.css`
在CSS中,我们将设置画布的背景为透明,并对整个网页设置背景图片:
- /* Set canvas and page styles */
- body {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- height: 100vh;
- margin: 0;
- background: url('background.jpg') no-repeat center center fixed; /* Background image */
- background-size: cover; /* Ensure the background covers the entire page */
- }
- h1 {
- color: #ffffff; /* White text color for better contrast */
- }
- #startButton {
- padding: 10px 20px;
- font-size: 16px;
- margin-bottom: 20px;
- background-color: #0000FF; /* Blue background */
- color: white; /* Text color white */
- border: none; /* No border */
- border-radius: 5px; /* Rounded corners */
- cursor: pointer; /* Pointer cursor on hover */
- }
- #startButton:hover {
- background-color: #0000cc; /* Darker blue on hover */
- }
- #gameCanvas {
- background-color: transparent; /* Transparent background to show the image behind */
- }
- #score {
- margin-top: 20px;
- font-size: 20px;
- color: #ffffff; /* White text color for better contrast */
- }
复制代码
#### `snake_game.js`
在JavaScript文件中,我们确保清除画布时不覆盖背景:
- // Get the canvas and set its context
- const canvas = document.getElementById('gameCanvas');
- const ctx = canvas.getContext('2d');
- const startButton = document.getElementById('startButton');
- const scoreDisplay = document.getElementById('score');
- // Define initial state
- let snake = [{ x: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }, { x: 120, y: 150 }, { x: 110, y: 150 }];
- let foodX;
- let foodY;
- let dx = 10;
- let dy = 0;
- let score = 0;
- let isGameRunning = false;
- let gameInterval;
- // Initialize the game
- function startGame() {
- snake = [{ x: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }, { x: 120, y: 150 }, { x: 110, y: 150 }];
- dx = 10;
- dy = 0;
- score = 0;
- isGameRunning = true;
- scoreDisplay.innerText = `Score: ${score}`;
- createFood();
- clearCanvas();
- drawSnake();
- drawFood();
- if (gameInterval) {
- clearInterval(gameInterval);
- }
- gameInterval = setInterval(main, 100); // Use setInterval instead of setTimeout
- }
- // Main game loop
- function main() {
- if (isGameRunning) {
- clearCanvas();
- moveSnake();
- drawSnake();
- drawFood();
- checkGameOver();
- } else {
- clearInterval(gameInterval);
- alert(`Game Over! Score: ${score}`);
- }
- }
- // Clear the canvas
- function clearCanvas() {
- ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas completely
- }
- // Draw the snake
- function drawSnake() {
- snake.forEach(snakePart => {
- ctx.fillStyle = 'lightgreen';
- ctx.strokeStyle = 'darkgreen';
- ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
- ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
- });
- }
- // Move the snake
- function moveSnake() {
- const head = { x: snake[0].x + dx, y: snake[0].y + dy };
- snake.unshift(head);
- const didEatFood = head.x === foodX && head.y === foodY;
- if (didEatFood) {
- score += 10;
- scoreDisplay.innerText = `Score: ${score}`;
- createFood();
- } else {
- snake.pop();
- }
- }
- // Randomly generate food position
- function createFood() {
- foodX = Math.floor(Math.random() * (canvas.width / 10)) * 10;
- foodY = Math.floor(Math.random() * (canvas.height / 10)) * 10;
- // Ensure food does not appear on the snake
- snake.forEach(function isFoodOnSnake(part) {
- const foodIsOnSnake = part.x === foodX && part.y === foodY;
- if (foodIsOnSnake) createFood();
- });
- }
- // Draw the food
- function drawFood() {
- ctx.fillStyle = 'red';
- ctx.strokeStyle = 'darkred';
- ctx.fillRect(foodX, foodY, 10, 10);
- ctx.strokeRect(foodX, foodY, 10, 10);
- }
- // Check if the game is over
- function checkGameOver() {
- for (let i = 4; i < snake.length; i++) {
- const hasCollided = snake[i].x === snake[0].x && snake[i].y === snake[0].y;
- if (hasCollided) isGameRunning = false;
- }
- const hitLeftWall = snake[0].x < 0;
- const hitRightWall = snake[0].x >= canvas.width;
- const hitTopWall = snake[0].y < 0;
- const hitBottomWall = snake[0].y >= canvas.height;
- if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) isGameRunning = false;
- }
- // Change direction
- document.addEventListener('keydown', changeDirection);
- 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;
- }
- }
- // Start button click event
- startButton.addEventListener('click', startGame);
复制代码
### 总结
将 `background.jpg` 图片放在与这三个文件相同的目录下,然后在浏览器中打开 `index.html` 文件,你就会看到带有图片背景的贪吃蛇游戏,画布背景将是透明的,使其与背景图片更好地融合。如果你有任何其他问题或进一步需求,请继续告诉我! |
|