|
|
贪吃蛇是一个经典的网页小游戏,在网页编程中可以使用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">
- <title>贪吃蛇</title>
- <style>
- #gameCanvas {
- width: 400px;
- height: 400px;
- border: 1px solid black;
- }
- </style>
- </head>
- <body>
- <canvas id="gameCanvas"></canvas>
- <script src="snake.js"></script>
- </body>
- </html>
复制代码
接下来,我们创建一个JavaScript文件(命名为snake.js),在其中实现贪吃蛇的游戏逻辑:
- const canvas = document.getElementById('gameCanvas');
- const ctx = canvas.getContext('2d');
- const box = 20;
- let snake = [{x: 10, y: 10}];
- let food = {x: 15, y: 15};
- let dx = 0;
- let dy = 0;
- function drawSnake() {
- snake.forEach(segment => {
- ctx.fillStyle = 'green';
- ctx.fillRect(segment.x * box, segment.y * box, box, box);
- });
- }
- function drawFood() {
- ctx.fillStyle = 'red';
- ctx.fillRect(food.x * box, food.y * box, box, box);
- }
- 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), y: Math.floor(Math.random() * 20)};
- } else {
- snake.pop();
- }
- }
- function updateGame() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- drawSnake();
- drawFood();
- moveSnake();
- }
- setInterval(updateGame, 100);
复制代码
这个简单的代码实现了一个基础的贪吃蛇游戏,玩家可以控制蛇的移动方向,吃到食物后蛇会变长。你可以尝试在这个基础上添加更多功能,比如增加难度、设计更复杂的地图等。希望你能喜欢这个小游戏! |
|