|
|
当然,以下是一个简单的贪吃蛇游戏的HTML、CSS和JavaScript代码。你可以将它们复制到三个分别命名为 index.html、style.css 和 script.js 的文件中,然后在浏览器中打开 index.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 id="game-board"></div>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
style.css:
- #game-board {
- width: 400px;
- height: 400px;
- border: 1px solid black;
- position: relative;
- }
- .snake {
- width: 10px;
- height: 10px;
- background-color: green;
- position: absolute;
- }
- .food {
- width: 10px;
- height: 10px;
- background-color: red;
- position: absolute;
- }
复制代码
script.js:
- const gameBoard = document.getElementById('game-board');
- let snake = [{x: 200, y: 200}];
- let food = {x: 100, y: 100};
- 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 + 10, y: snake[0].y};
- snake.unshift(head);
- if (head.x === food.x && head.y === food.y) {
- food.x = Math.floor(Math.random() * 39) * 10;
- food.y = Math.floor(Math.random() * 39) * 10;
- } else {
- snake.pop();
- }
- }
- drawSnake();
- drawFood();
- setInterval(() => {
- moveSnake();
- drawSnake();
- }, 100);
复制代码
将以上代码分别复制到对应的文件中,并确保这三个文件在同一目录下。然后用浏览器打开 index.html 文件,你就可以开始玩贪吃蛇游戏了!玩得开心哦!如果有其他问题,随时告诉我。 |
|