|
|
当初,我也是通过编写贪吃蛇游戏来学习网页编程的。让我们一起来创建一个简单的贪吃蛇游戏网页代码吧!
首先,我们需要三个文件:一个HTML文件(用于结构)、一个CSS文件(用于样式)、一个JS文件(用于逻辑)。
1. HTML文件(index.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">
- <div id="snake"></div>
- <div id="food"></div>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
2. CSS文件(style.css):
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- margin: 0;
- }
- .game-container {
- width: 300px;
- height: 300px;
- border: 1px solid #000;
- position: relative;
- }
- #snake, #food {
- width: 10px;
- height: 10px;
- background: black;
- position: absolute;
- }
复制代码
3. JS文件(script.js):
- const snake = document.getElementById('snake');
- const food = document.getElementById('food');
- let snakeX = 0;
- let snakeY = 0;
- let foodX = 0;
- let foodY = 0;
- let score = 0;
- function updateFoodPosition() {
- foodX = Math.floor(Math.random() * 30) * 10;
- foodY = Math.floor(Math.random() * 30) * 10;
-
- food.style.left = foodX + 'px';
- food.style.top = foodY + 'px';
- }
- function gameLoop() {
- snakeX += 10;
- snakeY += 0;
- snake.style.left = snakeX + 'px';
- snake.style.top = snakeY + 'px';
- if (snakeX === foodX && snakeY === foodY) {
- score++;
- updateFoodPosition();
- }
- setTimeout(gameLoop, 100);
- }
- updateFoodPosition();
- gameLoop();
复制代码
将这三份代码保存成对应的文件,放在同一个文件夹中并使用浏览器打开index.html文件,你就可以看到一个简单的贪吃蛇游戏了!不过,这只是一个基础版本,你可以尝试添加更多功能,比如让蛇可以移动、吃到食物增长长度等。加油! |
|