|
|
当我们创建一个网页贪吃蛇游戏时,首先要考虑的是蛇、食物和游戏区域的布局。下面我将分别为你介绍HTML、CSS和JavaScript代码。
### HTML部分
在HTML中,我们需要创建一个游戏区域和放置游戏的容器。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>贪吃蛇游戏</title>
- <link rel="stylesheet" href="style.css">
- </head>
- <body>
- <div class="game-container">
- <canvas id="gameCanvas"></canvas>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
### CSS部分
在CSS中,我们可以设置游戏区域的样式。
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- margin: 0;
- }
- .game-container {
- border: 2px solid #000;
- }
- #gameCanvas {
- border: 1px solid #000;
- }
复制代码
### JavaScript部分
在JavaScript中,我们需要编写游戏逻辑、蛇的移动和食物的生成等功能。
- const canvas = document.getElementById("gameCanvas");
- const ctx = canvas.getContext("2d");
- const box = 32;
- let snake = [];
- snake[0] = {
- x: 9 * box,
- y: 10 * box
- };
- let food = {
- x: Math.floor(Math.random() * 17 + 1) * box,
- y: Math.floor(Math.random() * 15 + 3) * box
- };
- function drawSnake() {
- for (let i = 0; i < snake.length; i++) {
- ctx.fillStyle = (i === 0) ? "green" : "white";
- ctx.fillRect(snake[i].x, snake[i].y, box, box);
- ctx.strokeStyle = "red";
- ctx.strokeRect(snake[i].x, snake[i].y, box, box);
- }
- }
- function drawFood() {
- ctx.fillStyle = "red";
- ctx.fillRect(food.x, food.y, box, box);
- }
- document.addEventListener("keydown", direction);
- let d;
- function direction(event) {
- if (event.keyCode == 37 && d != "RIGHT") {
- d = "LEFT";
- } else if (event.keyCode == 38 && d != "DOWN") {
- d = "UP";
- } else if (event.keyCode == 39 && d != "LEFT") {
- d = "RIGHT";
- } else if (event.keyCode == 40 && d != "UP") {
- d = "DOWN";
- }
- }
- function game() {
- drawSnake();
- drawFood();
- let snakeX = snake[0].x;
- let snakeY = snake[0].y;
- if (d === "LEFT") snakeX -= box;
- if (d === "UP") snakeY -= box;
- if (d === "RIGHT") snakeX += box;
- if (d === "DOWN") snakeY += box;
- if (snakeX === food.x && snakeY === food.y) {
- food = {
- x: Math.floor(Math.random() * 17 + 1) * box,
- y: Math.floor(Math.random() * 15 + 3) * box
- };
- } else {
- snake.pop();
- }
- let newHead = {
- x: snakeX,
- y: snakeY
- };
- snake.unshift(newHead);
- }
- let gameLoop = setInterval(game, 100);
复制代码
通过以上代码,你可以在浏览器中打开该HTML文件,即可看到一个简单的贪吃蛇游戏。希望对你有所帮助!如果有任何问题,都可以随时问我哦! |
|