|
|
当然可以!下面是一个简单的贪吃蛇游戏的HTML、CSS和JavaScript代码示例:
**HTML:**
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <title>贪吃蛇游戏</title>
- </head>
- <body>
- <div id="game">
- <canvas id="snakeCanvas" width="400" height="400"></canvas>
- </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 {
- text-align: center;
- }
- #snakeCanvas {
- border: 1px solid #000;
- }
复制代码
**JavaScript (script.js):**
- const canvas = document.getElementById('snakeCanvas');
- const ctx = canvas.getContext('2d');
- const box = 20;
- let snake = [
- {x: 10 * box, y: 10 * box},
- ];
- let food = {
- x: Math.floor(Math.random() * 20) * box,
- y: Math.floor(Math.random() * 20) * box,
- };
- function drawSnake() {
- snake.forEach(segment => {
- ctx.fillStyle = 'green';
- ctx.fillRect(segment.x, segment.y, box, box);
- });
- }
- function drawFood() {
- ctx.fillStyle = 'red';
- ctx.fillRect(food.x, food.y, box, box);
- }
- function draw() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- drawSnake();
- drawFood();
- }
- let game = setInterval(draw, 100);
- window.addEventListener('keydown', e => {
- const direction = e.key.replace('Arrow', '');
- // 控制蛇移动方向的逻辑
- });
- function moveSnake() {
- // 移动蛇的逻辑
- }
- function checkCollision() {
- // 检查碰撞的逻辑
- }
复制代码
请注意,这只是一个基本的贪吃蛇游戏框架,还可以根据需要进行扩展和优化。希望对你有所帮助!如果有任何问题,随时告诉我哦! |
|