|
|
当我们要创建一个贪吃蛇游戏的网页时,一般需要使用 HTML、JavaScript 和 CSS 这三种技术来完成。下面我会分块地给你展示每一部分的代码:
### 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" type="text/css" 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>
复制代码
### CSS (style.css)
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- margin: 0;
- }
- .game-container {
- width: 400px;
- height: 400px;
- border: 2px solid #000;
- position: relative;
- }
- #snake {
- width: 10px;
- height: 10px;
- background-color: green;
- position: absolute;
- }
- #food {
- width: 10px;
- height: 10px;
- background-color: red;
- position: absolute;
- }
复制代码
### JavaScript (script.js)
- const gameContainer = document.querySelector('.game-container');
- const snake = document.getElementById('snake');
- const food = document.getElementById('food');
- let snakeX = 0;
- let snakeY = 0;
- let foodX = 0;
- let foodY = 0;
- function updateSnake() {
- snake.style.left = snakeX + 'px';
- snake.style.top = snakeY + 'px';
- }
- function updateFood() {
- food.style.left = foodX + 'px';
- food.style.top = foodY + 'px';
- }
- function generateFood() {
- foodX = Math.floor(Math.random() * 39) * 10;
- foodY = Math.floor(Math.random() * 39) * 10;
- updateFood();
- }
- document.addEventListener('keydown', function(e) {
- if (e.key === 'ArrowRight') {
- snakeX += 10;
- } else if (e.key === 'ArrowLeft') {
- snakeX -= 10;
- } else if (e.key === 'ArrowDown') {
- snakeY += 10;
- } else if (e.key === 'ArrowUp') {
- snakeY -= 10;
- }
- updateSnake();
- // Check if snake eats food
- if (snakeX === foodX && snakeY === foodY) {
- generateFood();
- }
- });
- generateFood();
复制代码
以上就是一个简单的贪吃蛇游戏网页的代码示例。通过这段代码,你可以在网页上看到一个贪吃蛇游戏,并且可以通过方向键控制蛇的移动,让它吃到食物。希望对你有所帮助。如果还有其他问题,欢迎随时问我哦! |
|