|
|
当然可以!贪吃蛇是一个经典的小游戏,让我们一起来编写一个简单的贪吃蛇代码吧!
首先,我们来定义一些基本的变量:
- `canvas`:画布,用来显示游戏
- `ctx`:画笔,用来在画布上绘制图形
- `snake`:贪吃蛇的身体,存储蛇身每一节的坐标
- `food`:食物的坐标
- `direction`:贪吃蛇的移动方向
接下来,我们编写一些基本的函数:
1. `drawSnake`:绘制贪吃蛇的身体
2. `drawFood`:绘制食物
3. `move`:移动贪吃蛇
4. `main`:主函数,用来初始化游戏并开始游戏循环
最后,让我们把这些代码组合起来:
- const canvas = document.getElementById("gameCanvas");
- const ctx = canvas.getContext("2d");
- const snake = [
- { x: 10, y: 10 },
- { x: 10, y: 11 },
- { x: 10, y: 12 }
- ];
- let food = { x: 15, y: 15 };
- let direction = "right";
- function drawSnake() {
- ctx.fillStyle = "green";
- snake.forEach(segment => {
- ctx.fillRect(segment.x * 10, segment.y * 10, 10, 10);
- });
- }
- function drawFood() {
- ctx.fillStyle = "red";
- ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
- }
- function move() {
- const head = { x: snake[0].x, y: snake[0].y };
- if (direction === "up") {
- head.y--;
- } else if (direction === "down") {
- head.y++;
- } else if (direction === "left") {
- head.x--;
- } else if (direction === "right") {
- head.x++;
- }
- snake.unshift(head);
- if (head.x === food.x && head.y === food.y) {
- // 如果吃到食物,则生成新的食物
- food = {
- x: Math.floor(Math.random() * canvas.width / 10),
- y: Math.floor(Math.random() * canvas.height / 10)
- };
- } else {
- snake.pop();
- }
- }
- function main() {
- setInterval(() => {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- drawSnake();
- drawFood();
- move();
- }, 100);
- }
- main();
复制代码
在这个代码中,我们定义了一个简单的贪吃蛇游戏,包括贪吃蛇的移动、吃食物等功能。你可以在网页上创建一个画布元素,并将其id设置为"gameCanvas",然后将以上代码粘贴到网页的<script>标签中就可以运行这个贪吃蛇游戏了。希望你玩得开心!如果有任何问题,都可以随时问我哦! |
|