科学教育

搜索
查看: 502|回复: 1
打印 上一主题 下一主题

给我一个贪吃蛇代码,css,js,thm

[复制链接]

2

主题

3

帖子

17

积分

新手上路

Rank: 1

积分
17
跳转到指定楼层
楼主
发表于 2025-9-30 10:08:45 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
给我一个贪吃蛇代码,css,js,thm
回复

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
沙发
发表于 2025-9-30 10:08:51 | 只看该作者
当然可以!下面是一个简单的贪吃蛇游戏的HTML、CSS和JavaScript代码示例:

**HTML:**
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="UTF-8">
  5.   <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.   <link rel="stylesheet" href="style.css">
  7.   <title>贪吃蛇游戏</title>
  8. </head>
  9. <body>
  10.   <div id="game">
  11.     <canvas id="snakeCanvas" width="400" height="400"></canvas>
  12.   </div>
  13.   <script src="script.js"></script>
  14. </body>
  15. </html>
复制代码


**CSS (style.css):**
  1. body {
  2.   display: flex;
  3.   justify-content: center;
  4.   align-items: center;
  5.   height: 100vh;
  6.   margin: 0;
  7. }

  8. #game {
  9.   text-align: center;
  10. }

  11. #snakeCanvas {
  12.   border: 1px solid #000;
  13. }
复制代码


**JavaScript (script.js):**
  1. const canvas = document.getElementById('snakeCanvas');
  2. const ctx = canvas.getContext('2d');

  3. const box = 20;

  4. let snake = [
  5.   {x: 10 * box, y: 10 * box},
  6. ];

  7. let food = {
  8.   x: Math.floor(Math.random() * 20) * box,
  9.   y: Math.floor(Math.random() * 20) * box,
  10. };

  11. function drawSnake() {
  12.   snake.forEach(segment => {
  13.     ctx.fillStyle = 'green';
  14.     ctx.fillRect(segment.x, segment.y, box, box);
  15.   });
  16. }

  17. function drawFood() {
  18.   ctx.fillStyle = 'red';
  19.   ctx.fillRect(food.x, food.y, box, box);
  20. }

  21. function draw() {
  22.   ctx.clearRect(0, 0, canvas.width, canvas.height);
  23.   drawSnake();
  24.   drawFood();
  25. }

  26. let game = setInterval(draw, 100);

  27. window.addEventListener('keydown', e => {
  28.   const direction = e.key.replace('Arrow', '');
  29.   // 控制蛇移动方向的逻辑
  30. });

  31. function moveSnake() {
  32.   // 移动蛇的逻辑
  33. }

  34. function checkCollision() {
  35.   // 检查碰撞的逻辑
  36. }
复制代码


请注意,这只是一个基本的贪吃蛇游戏框架,还可以根据需要进行扩展和优化。希望对你有所帮助!如果有任何问题,随时告诉我哦!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表