基于 js 制作一个贪吃蛇小游戏

前言:

在工作学习之余玩一会游戏既能带来快乐,还能缓解生活压力,跟随此文一起制作一个小游戏吧。

描述:
贪吃蛇(也叫做贪食蛇)游戏是一款休闲益智类游戏,有PC和手机等多平台版本。既简单又耐玩。该游戏通过控制蛇头方向吃蛋,从而使得蛇变得越来越长。

功能按键:
W:向上
S:向下
A:向左
D:向右
其他:全部为暂停


项目效果展示:

在这里插入图片描述


代码实现思路:

  1. 设置需要使用的参数
  2. 双重 for 循环设置网格对象,使用随机数设置食物。
  3. 设置贪吃蛇对象,首先清空所有,然后根据保存的位置添加贪吃蛇
  4. 设置键盘按下事件
  5. 判断需要的几个按键,w,s,a,d(上,下,左,右)
  6. 判断是否撞墙,撞到墙则停止游戏。
  7. 判断是否吃到食物,食物消失,贪吃蛇长大
  8. 点击重新开始游戏

使用方法:

新建一个后缀为 HTML 的文件,然后把下面的代码复制进去,然后双击打开。
当然也可以直接通过下面链接进行下载,下载完成后双击打开即可。
点击进行下载:https://download.csdn.net/download/weixin_62897746/87377763


实现代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇</title>
    <style>
        body{
            text-align: center;
        }
        .box{
            margin: 0 auto;
            border: 1px solid #ddd;
            display: flex;
            flex-wrap: wrap;
        }
        .item{
            box-sizing: border-box;
            border: 1px solid #ddd;
        }
        .player{
            background-color: #444;
        }
        .eat{
            background-color: rosybrown;
        }
        #btn{
            margin-top: 20px;
            font-size: 23px;
            color: #fff;
            border: 1px solid #000;
            border-radius: 5px;
            padding: 10px 25px;
            background-image: linear-gradient(to right,#ff00ad,#f09876);
        }
    </style>
</head>
<body>
    <h1>贪吃蛇大作战</h1>
    <p id="text"></p>
    <div class="box"></div>
    <button id="btn">开始</button>
</body>
<script>
    sessionStorage.setItem('id',0)
    function kaishi(){
        // 行
        const x = 20
        // 列
        const y = 20
        // 盒子大小
        const size = 20
        // 地图
        const box = document.querySelectorAll('.box')[0]
        // 网格对象
        const result = []
        // 贪吃蛇对象
        const player = [
            [1,1]
        ]
        // 贪吃蛇对象
        const updatePlayer =()=>{
            // 清除所有对象
            document.querySelectorAll('.player').forEach(v=>v.classList.remove('player'))
            player.forEach(v=>{
                // 根据网格所在位置设置贪吃蛇对象,移动
                document.querySelector(`[data-v="${v.join('-')}"]`).classList.add('player')
            })
        }
        let key = ''
        // 循环设置网格
        for(let i=0; i<x; i++){
            for(let j=0; j<y; j++){
                // 随机数,食物
                const isEat = Math.random() > 0.9
                // 添加网格对象
                result.push(`<div data-v="${i}-${j}" class="item ${isEat ? 'eat' : ''}" style="width:${size}px;height:${size}px"></div>`)
            }
        }
        // 把内容转换为字符串
        box.innerHTML = result.join('')
        // 设置宽
        box.style.width = `${x*size}px`

        // 触发事件
        document.addEventListener('keydown',e=>{
            // 保存触发事件
            key = e.key
        })

        // 定时器
        const intervalId = setInterval(()=>{
            // 显示分数,和历史最高分
            document.getElementById('text').innerHTML = `当前分为${player.length}分,历史最高分为${sessionStorage.getItem('id')}`
            if(key){
                // 保存贪吃蛇所在位置
                const needPos = JSON.parse(JSON.stringify(player.slice(0,player.length-1)))
                // 判断触发事件
                switch(key){
                    case 'w':
                        player[0][0] -= 1
                        break;
                    case 'a':
                        player[0][1] -= 1
                        break;
                    case 's':
                        player[0][0] += 1
                        break;
                    case 'd':
                        player[0][1] += 1
                        break;
                }
                // 是否撞墙
                const el = document.querySelector(`[data-v="${player[0].join('-')}"]`)
                // 判断是否撞墙
                if(!el){
                    // 停止定时器
                    clearInterval(intervalId)
                    // 判断当前分是否超过历史最高分
                    if(sessionStorage.getItem('id') < player.length){
                        // 更改分数
                        sessionStorage.setItem('id',player.length)
                    }
                    alert('撞墙了')
                    isKey = true
                }else{
                    // 改变保存贪吃蛇的位置
                    for(let i=1; i<player.length; i++){
                        player[i] = needPos[i-1]
                    }
                    // 判断是否迟到食物
                    if(el.className.indexOf('eat') >= 0){
                        // 删除食物
                        el.classList.remove('eat')
                        // 贪吃蛇增长
                        player.push([...player[0]])
                    }
                    // 调用贪吃蛇使他发生改变
                    updatePlayer()
                }
            }
        },100)
        updatePlayer()
    }
    kaishi()
    let isKey = true
    // 点击开始
    document.getElementById('btn').onclick=()=>{
        if(isKey){
            kaishi()
            isKey = false
        }
    }
</script>
</html>

总结:

以上就是 基于 js 制作一个贪吃蛇小游戏,不懂得也可以在评论区里问我或私聊我询问,以后会持续发布一些新的功能,敬请关注。
我的其他文章:https://blog.csdn.net/weixin_62897746?type=blog

  • 25
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 37
    评论
以下是使用 Eclipse 制作贪吃蛇小游戏的步骤: 1. 创建 Java 项目 在 Eclipse 中创建一个新的 Java 项目,并命名为 SnakeGame。 2. 新建类 在 src 文件夹下创建一个名为 SnakeGame 的类。这个类将包含主方法,用于启动游戏。 3. 导入图形库 在 SnakeGame 类中导入 Java 的图形库,以便在游戏中创建图形界面。 ``` import java.awt.*; import javax.swing.*; ``` 4. 创建游戏窗口 在 SnakeGame 类中创建游戏窗口。这个窗口将包含游戏区域,用于显示贪吃蛇和食物。 ``` public class SnakeGame { public static void main(String[] args) { JFrame frame = new JFrame("Snake Game"); frame.setSize(500, 500); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ``` 5. 添加游戏区域 在 SnakeGame 类中添加游戏区域。这个区域将显示贪吃蛇和食物,并允许玩家控制贪吃蛇移动。 ``` public class SnakeGame { public static void main(String[] args) { JFrame frame = new JFrame("Snake Game"); frame.setSize(500, 500); JPanel gamePanel = new JPanel(); gamePanel.setBackground(Color.black); frame.add(gamePanel); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ``` 6. 添加贪吃蛇 在 SnakeGame 类中添加贪吃蛇。这个贪吃蛇将在游戏区域中移动,并吃掉食物。 ``` public class SnakeGame { public static void main(String[] args) { JFrame frame = new JFrame("Snake Game"); frame.setSize(500, 500); JPanel gamePanel = new JPanel(); gamePanel.setBackground(Color.black); gamePanel.setLayout(null); JLabel snake = new JLabel(); snake.setBounds(50, 50, 10, 10); snake.setBackground(Color.green); snake.setOpaque(true); gamePanel.add(snake); frame.add(gamePanel); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ``` 7. 添加食物 在 SnakeGame 类中添加食物。这个食物将在游戏区域中随机出现,并被贪吃蛇吃掉。 ``` public class SnakeGame { public static void main(String[] args) { JFrame frame = new JFrame("Snake Game"); frame.setSize(500, 500); JPanel gamePanel = new JPanel(); gamePanel.setBackground(Color.black); gamePanel.setLayout(null); JLabel snake = new JLabel(); snake.setBounds(50, 50, 10, 10); snake.setBackground(Color.green); snake.setOpaque(true); gamePanel.add(snake); JLabel food = new JLabel(); food.setBounds(100, 100, 10, 10); food.setBackground(Color.red); food.setOpaque(true); gamePanel.add(food); frame.add(gamePanel); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ``` 8. 控制贪吃蛇移动 在 SnakeGame 类中添加控制贪吃蛇移动的代码。这个代码将使贪吃蛇按照玩家的指令移动。 ``` public class SnakeGame { public static void main(String[] args) { JFrame frame = new JFrame("Snake Game"); frame.setSize(500, 500); JPanel gamePanel = new JPanel(); gamePanel.setBackground(Color.black); gamePanel.setLayout(null); JLabel snake = new JLabel(); snake.setBounds(50, 50, 10, 10); snake.setBackground(Color.green); snake.setOpaque(true); gamePanel.add(snake); JLabel food = new JLabel(); food.setBounds(100, 100, 10, 10); food.setBackground(Color.red); food.setOpaque(true); gamePanel.add(food); frame.add(gamePanel); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); int x = 0; int y = 0; while (true) { // 获取键盘输入 String input = JOptionPane.showInputDialog("Enter a direction (up, down, left, right):"); // 根据输入移动贪吃蛇 if (input.equals("up")) { y--; } else if (input.equals("down")) { y++; } else if (input.equals("left")) { x--; } else if (input.equals("right")) { x++; } // 移动贪吃蛇 snake.setBounds(snake.getX() + x, snake.getY() + y, 10, 10); } } } ``` 9. 完善游戏逻辑 在 SnakeGame 类中完善游戏逻辑。这个逻辑将使贪吃蛇可以正常地吃掉食物,并自动增长长度。 ``` public class SnakeGame { public static void main(String[] args) { JFrame frame = new JFrame("Snake Game"); frame.setSize(500, 500); JPanel gamePanel = new JPanel(); gamePanel.setBackground(Color.black); gamePanel.setLayout(null); JLabel snake = new JLabel(); snake.setBounds(50, 50, 10, 10); snake.setBackground(Color.green); snake.setOpaque(true); gamePanel.add(snake); JLabel food = new JLabel(); food.setBounds(100, 100, 10, 10); food.setBackground(Color.red); food.setOpaque(true); gamePanel.add(food); frame.add(gamePanel); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); int x = 0; int y = 0; while (true) { // 获取键盘输入 String input = JOptionPane.showInputDialog("Enter a direction (up, down, left, right):"); // 根据输入移动贪吃蛇 if (input.equals("up")) { y--; } else if (input.equals("down")) { y++; } else if (input.equals("left")) { x--; } else if (input.equals("right")) { x++; } // 移动贪吃蛇 snake.setBounds(snake.getX() + x, snake.getY() + y, 10, 10); // 判断贪吃蛇是否吃到食物 if (snake.getBounds().intersects(food.getBounds())) { // 食物被吃掉,重新生成食物 int fx = (int) (Math.random() * gamePanel.getWidth()); int fy = (int) (Math.random() * gamePanel.getHeight()); food.setBounds(fx, fy, 10, 10); // 贪吃蛇增加长度 JLabel body = new JLabel(); body.setBounds(snake.getX(), snake.getY(), 10, 10); body.setBackground(Color.green); body.setOpaque(true); gamePanel.add(body, 1); } // 判断贪吃蛇是否撞墙 if (snake.getX() < 0 || snake.getX() + snake.getWidth() > gamePanel.getWidth() || snake.getY() < 0 || snake.getY() + snake.getHeight() > gamePanel.getHeight()) { JOptionPane.showMessageDialog(null, "Game Over!"); System.exit(0); } // 判断贪吃蛇是否撞到自己 for (Component c : gamePanel.getComponents()) { if (c instanceof JLabel && !c.equals(snake) && snake.getBounds().intersects(c.getBounds())) { JOptionPane.showMessageDialog(null, "Game Over!"); System.exit(0); } } // 暂停一段时间 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 10. 运行游戏 最后,点击运行按钮,启动贪吃蛇小游戏

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 37
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清风 与我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值