|
|
当我们说要生成一个贪吃蛇的网页代码时,实际上是在编写一个简单的网页游戏。首先,我们需要使用 HTML 来构建页面的结构,然后使用 CSS 来设计页面的样式,最后使用 JavaScript 来编写游戏的逻辑。
下面是一个简单的贪吃蛇游戏的网页代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>贪吃蛇</title>
- <style>
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- margin: 0;
- }
- #game-board {
- width: 400px;
- height: 400px;
- border: 1px solid black;
- position: relative;
- }
- .snake {
- width: 20px;
- height: 20px;
- background-color: green;
- position: absolute;
- }
- .food {
- width: 20px;
- height: 20px;
- background-color: red;
- position: absolute;
- }
- </style>
- </head>
- <body>
- <div id="game-board"></div>
- <script>
- const gameBoard = document.getElementById('game-board');
- let snake = [{x: 200, y: 200}];
- let food = {x: 100, y: 100};
- let dx = 0;
- let dy = 0;
- function drawSnake() {
- gameBoard.innerHTML = '';
- snake.forEach(segment => {
- const snakeElement = document.createElement('div');
- snakeElement.style.left = segment.x + 'px';
- snakeElement.style.top = segment.y + 'px';
- snakeElement.classList.add('snake');
- gameBoard.appendChild(snakeElement);
- });
- }
- function drawFood() {
- const foodElement = document.createElement('div');
- foodElement.style.left = food.x + 'px';
- foodElement.style.top = food.y + 'px';
- foodElement.classList.add('food');
- gameBoard.appendChild(foodElement);
- }
- function moveSnake() {
- const head = {x: snake[0].x + dx, y: snake[0].y + dy};
- snake.unshift(head);
- if (head.x === food.x && head.y === food.y) {
- // 吃到食物,蛇变长
- food.x = Math.floor(Math.random() * 20) * 20;
- food.y = Math.floor(Math.random() * 20) * 20;
- } else {
- snake.pop();
- }
- }
- function main() {
- drawSnake();
- drawFood();
- moveSnake();
- }
- setInterval(main, 100);
- </script>
- </body>
- </html>
复制代码
在这段代码中,我们创建了一个 400x400 的游戏板,并定义了蛇和食物的样式,通过 JavaScript 实现了贪吃蛇游戏的基本逻辑:控制蛇的移动、食物的生成以及蛇的长度增加等功能。希望你能够根据这个例子做出属于自己的贪吃蛇网页游戏! |
|